Given an array like this:
[
{ force_x: [1, 2, 3], force_y: [0.3, 0.4, 0.5] },
{ force_x: [4, 5, 6], force_y: [0.0, 0.0, 0.0] },
{ motion_x: [0.7, 0.7, 0.7] }
]
How could I use Javascript to reduce this to an array like this without specifying any keys:
[
{ force_x: 1, force_y: 0.3 },
{ force_x: 2, force_y: 0.4 },
{ force_x: 3, force_y: 0.5 },
{ force_x: 4, force_y: 0.0 },
{ force_x: 5, force_y: 0.0 },
{ force_x: 6, force_y: 0.0 },
{ motion_x: 0.7 },
{ motion_x: 0.7 },
{ motion_x: 0.7 }
]
This answer could work but I don't want to specify the key name, I want it to do it for every keys automatically.
const output = input.flatMap(o =>
o.emailAddresses.map(e => ({force_x: e }) )
)
1 Answer 1
You can use Object.entries to get all the key value pairs and work with that.
let arr=[{force_x:[1,2,3],force_y:[.3,.4,.5]},{force_x:[4,5,6],force_y:[0,0,0]},{motion_x:[.7,.7,.7]}];
let res = arr.flatMap(x => {
const entries = Object.entries(x);
return entries[0][1].map((_, i) => Object.fromEntries(
entries.map(([k, v]) => [k, v[i]])));
});
console.log(res);
answered Sep 30, 2022 at 14:07
Unmitigated
91.5k12 gold badges103 silver badges109 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Captain Yoshi
Nice! Thank you very much. Coming from c++ land, so this is all black magic to me :)
vsync
this works well as long as the number of items per array is the same for all keys. A preferred solution would not create keys for non-existing array items. For example, change
force_x:[1,2,3] to force_x:[1]lang-js