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

195
Views
agregue cantidad para objetos json similares en javascript

Quiero que el resultado sea sumar todas las cantidades del mismo gato.

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

Intenté así a continuación. Tengo una matriz de objetos que tienen algunos objetos similares. cómo agregar cantidad y crear objetos únicos. A continuación he dado lo que probé.

 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

Puedes hacer esto usando Array#reduce , usando el acumulador para pasar el nuevo objeto:

 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!