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

218
Visualizações
How do I reformat this JSON data by creating a key from a section of the data?

I'd like to reformat data by taking a section of one JSON entry. For example, I have JSON data:

{ "AXD:Condor": 12,
 "AXD:Pelican": 20,
 "GPR:Deer": 15,
 "GPR:Owl": 34
}

and I would like to have reformat it to something like this:

{ AXD:{
     Condor: 12,
     Pelican:20
 }
  GPR:{
     Deer: 15,
     Owl: 34
 }
}

I apologize if this question is obvious or badly worded, I'm quite new to using JSON. Thanks for taking the time to answer.

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

0

Using Object.entries(data) we are getting an array with the key-value pairs of the data object. Then we iterate through this array using reduce, where [key, value] is the object's pair and a is the accumulator whose initial value is an empty object {} (check the end of the function) and will be the result.

Now for each iteration, we split our key value and keep the first part that we want to use as our new key. Then we check if the accumulator object already contains that key from a previous iteration, and if not we add it and assign an empty object to it. Lastly, we assign the old key-value pair inside this newly assigned key so that we can have the nested result we want.

const data = { 
 "AXD:Condor": 12,
 "AXD:Pelican": 20,
 "GPR:Deer": 15,
 "GPR:Owl": 34
}

let res = Object.entries(data).reduce((a, [key, value]) => {
  let outerKey = key.split(':')[0];
  
  if (!a[outerKey]) {
    a[outerKey] = {};
  }
  
  a[outerKey][key] = value;
  return a;
}, {});

console.log(res);

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