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

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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