1

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 }) )
)
asked Sep 30, 2022 at 14:01

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Thank you very much. Coming from c++ land, so this is all black magic to me :)
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]

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.