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

Viewed 45

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,
      }
    ]
  }
]
5 Answers

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);

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);

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

Lodash fp if you don't mind

const 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 }]}];

const result = _(xyz).flatMap('product').sumBy('qty');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

You need a nested loop. Array#reduce will do the trick.

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,
      }
    ]
  }
]

const quantity = (input) =>
    input.reduce((p, { product }) => 
        p + product.reduce((p, { qty }) => p + qty, 0), 0)

console.log(quantity(xyz)) // 10

Related