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
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 }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:
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)