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

111
Vistas
Group object key values to a new object with same structure

I have this JSON and I need to group in a new object by key:

[
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
]

Expected Final Result:

    {
        "product": ["name 1", "name 2", "name 3"],
        "price": ["3000", "1000", "5000"],
        "inspection": [false, true, false]
    }

I tried to use -> for, foreach <- but not getting a good/optimum result. I also considered using reduce but I couldn't get it to work.

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

0

let data = [
    {
        "product": "name 1",
        "price": "3000",
        "inspection": false,
    },
    {
        "product": "name 2",
        "price": "1000",
        "inspection": true,
    },
    {
        "product": "name 3",
        "price": "5000",
        "inspection": false,
    },
];

let output = Object.fromEntries(
  Object.keys(data[0]).map(k => 
    [k, data.map(d => d[k])]
  )
);

console.log(output);

about 4 years ago · Juan Pablo Isaza Denunciar

0

For objects of any shape, this'll group items under any key:

const arr = [
  { product: "name 1", price: 3000, inspection: false },
  { product: "name 2", price: 1000, inspection: true },
  { product: "name 3", price: 5000, inspection: false },
]

const groups = arr.reduce((groups, obj) =>
  Object.entries(obj).reduce((groups, [key, val]) => (
    { ...groups, [key]: (groups[key]??[]).concat(val) }
  ), groups)
, {})

console.log(groups)

Which keys get grouped may be changed by filtering the result of Object.entries(obj) by key.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Presented below is one possible way to achieve the desired objective.

Code Snippet

// one possible method to transform given array
const myTransform = arr => (
  arr.reduce(
    (acc, { product, price, inspection }) => (
      (acc.product ??= []).push(product),
      (acc.price ??= []).push(name),
      (acc.inspection ??= []).push(inspection),
      acc
    ),
    {}
  )
);

// using a simple for loop:
const myTransform2 = arr => {
  // initialize result "res" as empty object
  const res = {};
  
  // iterate over each elt in array "arr"
  for ({ product, price, inspection } of arr) {
    // if res has no key product, add one with value as empty array
    // push the "product" to the above key
    (res.product ??= []).push(product);
    // same logic for price
    (res.price ??= []).push(name);
    // same for inspection
    (res.inspection ??= []).push(inspection);
  };
  // return the result
  return res;
};

const dataArr = [{
    "product": "name 1",
    "price": "3000",
    "inspection": false,
  },
  {
    "product": "name 2",
    "price": "1000",
    "inspection": true,
  },
  {
    "product": "name 3",
    "price": "5000",
    "inspection": false,
  },
];

console.log(
  'transformed array:\n',
  myTransform(dataArr)
);

console.log(
  'transformed array using for loop:\n',
  myTransform2(dataArr)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Comments added to the snippet above.

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