Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
How to add a lable to an object value in javascript

I have an array of objects that is grouped by index and would like to restructure and add labels to the response.

This is my original array:

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'}]

Here is the source code used to group the array by make:

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

The response looks like this:

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

My desired outcome should look like this:

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

Is this possible to achieve using JavaScript? If so can I get assistance to achieve this task.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

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 Denunciar

0

You can use array.reduce to turn one array into another one and control whether you return a new element or accumulate values in existing one (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 Denunciar

0

If you want to keep your groupby as-is (using 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda