I have the following array with one object:
[{
"0key1": "a33",
"0key2": "Aab",
"0key3": "i",
"1key1": "e78",
"1key2": "Vib",
"1key3": "j",
"2key1": "c99",
"2key2": "Aig",
"2key3": "k"
}]
I would like to split it into three "key": "value" per row as shown below:
[
{"0key1":"a33","0key2":"Aab","0key3":"i"},
{"1key1":"e78","1key2":"Vib","1key3":"j"},
{"2key1":"c99","2key2":"Aig","2key3":"k"}
]
Please help me achieve that.
>Solution :
I would use reduce and a nullish coalescing assigment
const input = [{
"0key1": "a33", "0key2": "Aab", "0key3": "i",
"1key1": "e78", "1key2": "Vib", "1key3": "j",
"2key1": "c99", "2key2": "Aig", "2key3": "k"
}]
const output = Object.entries(input[0]).reduce((acc,cur) => {
const key = cur[0];
const [mainIdx,idx] = key.split("key");
acc[mainIdx] ??= {}; // nullish coalescing assignment
acc[mainIdx][key]=cur[1];
return acc;
}
,[])
console.log(output)