I have a JSON object in the below format which I want to convert into a JSON array. I have tried multiple ways to achieve this, but I can not get success.
{
"name":{
"0":"mike",
"1":"george",
"2":"Andrew"
},
"category":{
"0":"A",
"1":"B",
"2":"C"
}
}
The output would be like this:
{
"0":{
"name":"mike",
"category":"A"
},
"1":{
"name":"george",
"category":"B"
},
"2":{
"name":"andrew",
"category":"C"
}
}
I am new to JSON. How can I achieve this?
You can make use of Object.keys and Object.entries
const obj = {
name: {
"0": "mike",
"1": "george",
"2": "Andrew",
},
category: {
"0": "A",
"1": "B",
"2": "C",
},
};
const props = Object.keys(obj);
const result = props.reduce((acc, key) => {
Object.entries(obj[key]).forEach(([k, v]) => {
if (!acc[k]) acc[k] = Object.fromEntries(props.map((p) => [p, ""]));
acc[k][key] = v;
});
return acc;
}, {});
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }