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

279
Views
JavaScript: agrupa objetos de matriz por atributo en un objeto con una lista

Actualmente estoy trabajando en un proyecto en el que tengo una serie de objetos, cada uno con "atributo" y "variación".

Necesito agruparlos como un objeto por atributo que tenga el "atributo" y una lista de "variaciones".

Entrada de muestra:

 [ { "attribute": "Pack", "variation": "full" }, { "attribute": "Size", "variation": "M" }, { "attribute": "Color", "variation": "blue" }, { "attribute": "Size", "variation": "X" }, { "attribute": "Color", "variation": "red" }, { "attribute": "Pack", "variation": "half" } ]

Rendimiento esperado:

 [ { "attribute": "Pack", "variations": ["full", "half" ] }, { "attribute": "Size", "variations": ["M", "X"] }, { "attribute": "Color", "variations": ["blue", "red"] }, ]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  • Usando Array#reduce , itere sobre la matriz mientras actualiza un acumulador de objetos donde el atributo es la key y el objeto correspondiente (atributo y variaciones) es el value . En cada iteración, para actualizar las variaciones, debe verificar si ya existe un registro existente para el atributo actual de acc con una lista de variations (puede usar optional-chaining ) y establecer un valor predeterminado de una matriz vacía (usted puede usar nullish-coalescing-operator )
  • Usando Object#values , devuelva la lista de objetos agrupados, cada uno con atributo y variaciones

 const arr = [ { "attribute": "Pack", "variation": "full" }, { "attribute": "Size", "variation": "M" }, { "attribute": "Color", "variation": "blue" }, { "attribute": "Size", "variation": "X" }, { "attribute": "Color", "variation": "red" }, { "attribute": "Pack", "variation": "half" } ]; const res = Object.values( arr.reduce((acc, { attribute, variation }) => ({ ...acc, [attribute]: { attribute, variations: [...(acc[attribute]?.variations ?? []), variation] } }), {}) ); console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

Puedes probar esto:

 let inputObjs = [ { "attribute": "Pack", "variation": "full" }, { "attribute": "Size", "variation": "M" }, { "attribute": "Color", "variation": "blue" }, { "attribute": "Size", "variation": "X" }, { "attribute": "Color", "variation": "red" }, { "attribute": "Pack", "variation": "half" } ]; let grouped = []; let attributeIndex = {}; let groupedIndex = 0; for(k = 0; k < inputObjs.length;k++){ const obj = inputObjs[k]; const attrKey = `_${obj.attribute}`; if(typeof attributeIndex[attrKey] != 'undefined'){ //console.log(grouped[attributeIndex[attrKey]].variations,grouped[attributeIndex[attrKey]].variations.indexOf(obj.variation),obj.variation); if(grouped[attributeIndex[attrKey]].variations.indexOf(obj.variation) == -1){ grouped[attributeIndex[attrKey]].variations.push(obj.variation); } }else{ attributeIndex[attrKey] = groupedIndex; grouped[attributeIndex[attrKey]] = {attribute:obj.attribute,variations:[]}; grouped[attributeIndex[attrKey]].variations.push(obj.variation); groupedIndex += 1; } //console.log(obj); } console.log(grouped); //console.log(attributeIndex);

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!