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

252
Views
Refactorización del recorrido de objetos de Javascript

El código que tengo da como resultado el resultado deseado. Sin embargo, en mi opinión, usar estos bucles for anidados es un poco feo y estoy tratando de refactorizar mi trabajo.

Mi pregunta es: ¿tiene alguna sugerencia sobre cómo refactorizar el código para que pueda evitar la necesidad de usar estos bucles for anidados?

Quiero recorrer un objeto anidado y terminar con un resultado de todas las claves únicas y una matriz de todos los valores para esa clave única.

 {"ABC":["1","100","6"],"DEF":["10","2","5"],"GHI":["14","9"],"HGI":["4"]} 

 const data = { something: [ { innerSomething: { list: [ { title: "ABC", amount: "1" }, { title: "DEF", amount: "10" }, { title: "GHI", amount: "14" } ], } }, { innerSomething: { list: [ { title: "ABC", amount: "100" }, { title: "DEF", amount: "2" }, { title: "GHI", amount: "9" } ], } }, { innerSomething: { list: [ { title: "ABC", amount: "6" }, { title: "DEF", amount: "5" }, { title: "HGI", amount: "4" } ], } } ] }; const results = {}; data.something.forEach((item) => { item.innerSomething.list.forEach((list) => { if (results[list.title]) { // exists already, just push the amount results[list.title].push(list.amount) } else { // Is unique so far, add it to the object results[list.title] = [list.amount]; } }) }); console.log(`results: ${JSON.stringify(results)}`); // These results are the correct and desired output // {"ABC":["1","100","6"],"DEF":["10","2","5"],"GHI":["14","9"],"HGI":["4"]}

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

0

Por lo que vale, así es como lo escribiría.

 const data = { something: [ { innerSomething: { list: [ { title: "ABC", amount: "1" }, { title: "DEF", amount: "10" }, { title: "GHI", amount: "14" } ], } }, { innerSomething: { list: [ { title: "ABC", amount: "100" }, { title: "DEF", amount: "2" }, { title: "GHI", amount: "9" } ], } }, { innerSomething: { list: [ { title: "ABC", amount: "6" }, { title: "DEF", amount: "5" }, { title: "GHI", amount: "4" } ], } } ] }; const results = {}; for (let something of data.something) { for (let item of something.innerSomething.list) { const { title, amount } = item; results[title] = results[title] || []; results[title].push(amount); } } console.log(`results: ${JSON.stringify(results)}`);

about 4 years ago · Juan Pablo Isaza Report

0

Su implementación está bien, tbh. Lo único que puedo sugerir de manera diferente es hacer uso de los patrones de desestructuración ordenados y la sintaxis extendida, considerando que la estructura de su objeto de entrada es muy conocida:

 data.something.forEach(({ innerSomething: { list } }) => list.forEach(({ title, amount }) => results[title] = [...results[title] || [], amount]))
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!