Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Use un atributo de objeto para crear una matriz con él

hola chicos quiero hacer algo "sencillo" pero no para mi, tengo esta matriz

 [ { x: 'bmw', vehicule_type: car, y: 1 }, { x: 'mercedes', vehicule_type: car, y: 2 }, { x: 'airbus', vehicule_type: plane, y: 1 } ]

Y quiero transformarlo en esta cosa

 [ car : [{ x: 'bmw', y: 1 }, { x: 'mercedes', y: 1 }] plane: [{ x: 'airbus', y: 1 }] ]

No puedo encontrar la manera de hacerlo, vi que podía usar "reductor ()" pero por lo demás estoy perdido

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

A continuación se presenta una posible forma de lograr el objetivo deseado.

Fragmento de código

 const myTransform = arr => ( arr.reduce( (acc, {vehicule_type, ...rest}) => ( (acc[vehicule_type] ??= []).push({...rest}), acc ), {} ) ); /* EXPLANATION of the code // method to transform the array const myTransform = arr => ( arr.reduce( // iterate using ".reduce()" with "acc" as accumulator // destructure the iterator to acces "vehicule_type" (acc, {vehicule_type, ...rest}) => ( // if "acc" doesn't have "vehicule_type", set it as empty array // and then, push "rest" (ie, x, y, other props, if any) into the array (acc[vehicule_type] ??= []).push({...rest}), // implicit return of "acc" acc ), {} // initialize "acc" as an empty object ) ); */ const dataArr = [ { x: 'bmw', vehicule_type: 'car', y: 1 }, { x: 'mercedes', vehicule_type: 'car', y: 2 }, { x: 'airbus', vehicule_type: 'plane', y: 1 } ]; console.log(myTransform(dataArr));
 .as-console-wrapper { max-height: 100% !important; top: 0 }

Explicación

Se agregaron comentarios en línea al fragmento anterior.

EDITAR

Como señaló Bergi en un comentario a continuación, también es posible usar un bucle for alternativo. Esto puede verse algo como se muestra a continuación:

 const myTransform = arr => { const res = {}; for (const {vehicule_type, ...rest} of dataArr) { (res[vehicule_type] ??= []).push({...rest}); }; return res; }; /* EXPLANATION // alternative method to transform the array const myTransform = arr => { // set up result "res" as an empty object "{}" const res = {}; // iterate over elts of "dataArr" // destructure the iterator to directly access "vehicule_type" for (const {vehicule_type, ...rest} of dataArr) { // if "vehicule_type" not already in "res", // then, set it with a value of empty array // push the remaining props "...rest" into the array (res[vehicule_type] ??= []).push({...rest}); }; // return the result return res; }; */ const dataArr = [ { x: 'bmw', vehicule_type: 'car', y: 1 }, { x: 'mercedes', vehicule_type: 'car', y: 2 }, { x: 'airbus', vehicule_type: 'plane', y: 1 } ]; console.log(myTransform(dataArr));
 .as-console-wrapper { max-height: 100% !important; top: 0 }

about 4 years ago · Juan Pablo Isaza Relatório

0

Puede agrupar los datos por vehicle_type utilizando Array.prototype.reduce .

 const data = [ { x: "bmw", vehicle_type: "car", y: 1 }, { x: "mercedes", vehicle_type: "car", y: 2 }, { x: "airbus", vehicle_type: "plane", y: 1 }, ], result = data.reduce( (r, { vehicle_type: t, ...o }) => ((r[t] ??= []).push(o), r), {} ); console.log(result);

Si le resulta difícil entender la solución anterior, consulte esta versión más descriptiva:

 const data = [ { x: "bmw", vehicle_type: "car", y: 1 }, { x: "mercedes", vehicle_type: "car", y: 2 }, { x: "airbus", vehicle_type: "plane", y: 1 }, ], result = data.reduce((r, { vehicle_type: t, ...o }) => { if (!r[t]) { r[t] = []; } r[t].push(o); return r; }, {}); console.log(result);

Documentaciones relevantes:

  • Operador coalescente nulo (??)
  • Parámetros de descanso
  • Desestructuración de objetos
  • Operador de coma (,)
about 4 years ago · Juan Pablo Isaza Relatório

0

No estoy seguro de si esta es la mejor manera de hacerlo; probablemente no, pero esto es lo que se me ocurrió...

 let array = [{ x: 'bmw', vehicle_type: "car", y: 1 }, { x: 'mercedes', vehicle_type: "car", y: 2 }, { x: 'airbus', vehicle_type: 'plane', y: 1 }, { x: 'mercedes', vehicle_type: "car", y: 2 } ] function sortByType(array) { const vehicles = {}; for (let object of array) { let vehicle = {}, type = undefined; for (let property in object) { if (type === undefined) type = object["vehicle_type"]; if (vehicles[type] === undefined) vehicles[type] = []; if (property === "vehicle_type") continue; vehicle[property] = object[property]; } vehicles[type].push(vehicle); } return vehicles } const vehicles = sortByType(array) console.log(vehicles)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda