You can transform your object around to get your desired result, first, transform your object to the following using .map()
with Object.entries()
:
[
[
{
"service": "A"
},
{
"service": "B"
}
],
[
{
"cost": 20
},
{
"cost": 50
}
]
]
Next, zip these two inner arrays together (the first element of the first array gets grouped with the first element of the second array, the second element of the first array gets grouped with the second element of the second array), using Object.assign()
as the grouping method:
const obj = {"service":[["A"],["B"]],"cost":[[20],[50]]};
const [first, ...r] = Object.entries(obj).map(([k,vals]) => vals.map(([v]) => ({[k]: v})));
const zipped = first.map((o, i) => Object.assign(o, ...r.map(arr => arr[i])));
console.log(zipped);
We can take a similar approach using Object.fromEntries()
:
const obj = {"service":[["A"],["B"]],"cost":[[20],[50]]};
const [first, ...r] = Object.entries(obj).map(
([k,vals]) => vals.map(([v]) => [k, v])
);
const zipped = first.map((entry, i) => Object.fromEntries(
[entry, ...r.map(arr => arr[i])]
));
console.log(zipped);
3
solved Turning an object with arrays as properties into an array of objects