Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
add qty for similar json objects in javascript

I want the result to be summing all the qty of same cat.

        var  data = [
             { cat: 'EK-1',name:"test",info:"mat", quantity: 3},
             { cat: 'EK-2', name:"test2",info:"nat"quantity: 1}
              ];

I tried like this below i have array of object having some similar objects. how to add qty and create unque objects .below i have given what i tried.

var data = [{
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-2',
    name: "test2",
    info: "nat",
    quantity: 1
  }
];

const products = Array.from(data.reduce((acc, {
    cat,
    quantity
  }) =>
  acc.set(cat, (acc.get(cat) || 0) + quantity),
  new Map()
), ([cat, quantity]) => ({
  cat,
  quantity
}));

console.log(products);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do this using Array#reduce, using the accumulator to pass on the new object:

var data = [ { cat: "EK-1", name: "test", info: "mat", quantity: 1, }, { cat: "EK-1", name: "test", info: "mat", quantity: 1, }, { cat: "EK-1", name: "test", info: "mat", quantity: 1, }, { cat: "EK-2", name: "test2", info: "nat", quantity: 1, }, ];

let seen = [];
const res = data.reduce((acc, { cat, ...rest }) => {
  const idx = seen.indexOf(cat);
  if (idx == -1) (acc.push({cat, ...rest}), seen.push(cat));
  else acc[idx].quantity++;
  return acc;
}, []);

console.log(res);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!