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

106
Views
Cómo agregar una etiqueta a un valor de objeto en javascript

Tengo una matriz de objetos agrupados por índice y me gustaría reestructurar y agregar etiquetas a la respuesta.

Esta es mi matriz original:

 let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]

Aquí está el código fuente utilizado para agrupar la matriz por marca:

 var groupedByMake = _.groupBy( cars, "make" );

La respuesta se ve así:

 { 'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}], 'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}] }

Mi resultado deseado debería verse así:

 [{ 'make': 'audi', 'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}] },{ 'make': 'bmw', 'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}] }]

¿Es posible lograr esto usando JavaScript? Si es así, ¿puedo obtener ayuda para lograr esta tarea?

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

0

 const cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]; const groupBy = (array, key) => { return array.reduce((acc, item) => { const keyValue = item[key]; const existingGroup = acc.find((group) => group.key === keyValue); if (existingGroup) { existingGroup.items.push(item); } else { // remove make from item const { make, ...rest } = item; acc.push({ key: keyValue, items: [rest] }); } return acc; }, []); } console.log(JSON.stringify(groupBy(cars, 'make'), null, 2));

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar array.reduce para convertir una matriz en otra y controlar si devuelve un nuevo elemento o acumula valores en uno existente ( prev ):

 let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]; let output = cars.reduce((acc, cur) => { let {make, ...obj} = cur; let prev = acc.find(x => x.make === make); if(!prev) { acc.push({make,types:[obj]}) } else { prev.types.push(obj); } return acc; }, []); console.log(output);

about 4 years ago · Juan Pablo Isaza Report

0

Si desea mantener su groupby tal como está (usando lodash):

 // Result from lodash var groupedByMake = { 'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}], 'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}] } const result = Object.keys(groupedByMake).map(make => ({make, types: groupedByMake [make]})); console.log(result);

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!