Calculation based on json response

Viewed 54

Suppose I have JSON response similar to

[
  {productName:"nord128",quantiy: 4},
  {productName:"nord128", quantiy:5},
  {productName:"nord128", quantiy:8},
  {productName:"Iphone11",quantiy:3},
  {productName:"nord128",quantiy:6}
]

How can I create an array which contains productName with its total value in an array,

[[nord128,23],[Iphone11,3]]

I tried,

res.forEach((element) => {
  array.push([element.productName, element.quantity])
})
 

Got result as an array,

[["nord128",4],["nord128",5],["nord128",8],["Iphone11",3]["nord128",6]]

but when I am comparing the next element of the array to the current element getting an error.

for (let i = 0; i < array.length - 1; i++) {
  if (array[i][0] === array[i + 1][0]) {
    /// some condition
  }
}

Getting error as array[i+1][0]// here 0 is undefined

1 Answers

You can use Array.reduce to create an accumulator object that calculates the total based on productName

var x = [{
    productName: "nord128",
    quantiy: 4
  },
  {
    productName: "nord128",
    quantiy: 5
  },
  {
    productName: "nord128",
    quantiy: 8
  },
  {
    productName: "Iphone11",
    quantiy: 3
  },
  {
    productName: "nord128",
    quantiy: 6
  }
];

const obj = x.reduce(function (acc, val) {
  acc[val.productName] = val.quantiy + (acc[val.productName] || 0)
  return acc
}, {})

console.log({
  obj
})

Related