Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten nested array key value pairs without specifying each key in Javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const output = input.flatMap(o => 
    o.emailAddresses.map(e => ({force_x: e }) )
)

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading