Krish Varma
Krish Varma

Reputation: 33

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

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

Upvotes: 0

Views: 60

Answers (5)

A1exandr Belan
A1exandr Belan

Reputation: 4780

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/[email protected]/lodash.min.js"></script>

Upvotes: 1

Ben Aston
Ben Aston

Reputation: 55729

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

Upvotes: 0

Med Jelidi
Med Jelidi

Reputation: 19

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

Upvotes: 1

Mara Black
Mara Black

Reputation: 1751

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

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 2

Related Questions