How am I able to convert the following object:
data = {
sp: [ 'A', 'B', 'C' ],
jh: [ '1', '0', 'AB' ],
oa: [ 27493, 9837, 3781 ]
}
into the following array of objects:
new_data = [
{sp: 'A', jh: '1', oa: 27493},
{sp: 'B', jh: '0', oa: 9837},
{sp: 'C', jh: 'AB', oa: 3781}
]
Assuming the arrays are all the same size, map one of them and reduce the keys using the current index.
const data = {
sp: [ 'A', 'B', 'C' ],
jh: [ '1', '0', 'AB' ],
oa: [ 27493, 9837, 3781 ]
};
let keys = Object.keys(data);
let new_data = data[keys[0]].map(( _, idx ) => keys.reduce((a, c) => ({ ...a, [c]: data[c][idx] }), {}));
console.log(new_data)
.as-console-wrapper { max-height: 100% !important; top: auto; }
Object.entries to get all of the key-value pairs in the object.Object.fromEntries to create an object with the keys from the original object and the value being the value at that index in the array for that key in the original object.const data = {
sp: [ 'A', 'B', 'C' ],
jh: [ '1', '0', 'AB' ],
oa: [ 27493, 9837, 3781 ]
}
let entries = Object.entries(data);
let res = entries[0][1].map((_, i)=>Object.fromEntries(
entries.map(([k, v])=>[k, v[i]])));
console.log(res);