• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

148
Vistas
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 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda