Home > Blockchain >  how can i get sum of all the qty from nested array object
how can i get sum of all the qty from nested array object

Time:09-15

I want to get sum of the qty values from the data. I tried, but I am only getting the total qty for the first item in the array.

I just want the result 10 from below (4 5 0 1)

let xyz = [{
    catid: '1',
    catName: 'abc',
    product: [{
        id: 1,
        qty: 4,
      },
      {
        id: 2,
        qty: 5,
      }
    ]
  },
  {
    catid: '2',
    catName: 'efg',
    product: [{
        id: 3,
        qty: 0,
      },
      {
        id: 4,
        qty: 1,
      }
    ]
  }
]

CodePudding user response:

To do what you require you can use reduce(). You will need to nest two reduce() calls, one to sum the inner qty for each product, then another to sum the total for all products:

let xyz = [ {catid: "1", catName: "abc", product: [{ id: 1, qty: 4 }, { id: 2, qty: 5 }]},{ catid: "2", catName: "efg", product: [{ id: 3, qty: 0 },{ id: 4, qty: 1 }]}];

var total = xyz.reduce((t0, o) => t0   o.product.reduce((t1, prod) => t1   prod.qty, 0), 0);
console.log(total);

CodePudding user response:

Uglier way with 2 forEach..

let xyz = [{
    catid: '1',
    catName: 'abc',
    product: [{
        id: 1,
        qty: 4,
      },
      {
        id: 2,
        qty: 5,
      }
    ]
  },
  {
    catid: '2',
    catName: 'efg',
    product: [{
        id: 3,
        qty: 0,
      },
      {
        id: 4,
        qty: 1,
      }
    ]
  }
]

let sum = 0;

xyz.forEach(element => {
  element.product.forEach(product => {
    sum  = product['qty'];
  });
});

console.log(sum);

CodePudding user response:

let totalqTy = 0;
xyz.forEach(o => {
  totalqTy  = o.product.map(p => p.qty).reduce(((previousValue, currentValue) => previousValue   currentValue));
});
  • Related