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.
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);