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

Get a one-dimensional array from an array of objects

I have the following array of objects:

const input = [
  { key1: 1, key2: 1, key3: 5 },
  { key1: 2, key2: 5, key3: 6 },
  { key1: 4, key2: 6, key3: 7 },
  { key1: 7, key2: 8, key3: 9 },
];

I just want to loop through an array of objects and collect all the values ​​into a one dimensional array like this:

const output = [1, 1, 5, 2, 5, 6, 4, 6, 7, 7, 8, 9];

Can someone help solve this problem?

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

>Solution :

If the keys are always in that order, you can use Object.values as a callback to flatMap

const output = input.flatMap(Object.values)
const input = [
  { key1: 1, key2: 1, key3: 5 },
  { key1: 2, key2: 5, key3: 6 },
  { key1: 4, key2: 6, key3: 7 },
  { key1: 7, key2: 8, key3: 9 },
];

const output = input.flatMap(Object.values)

console.log(output)

Relying the order of keys in an object is generally NOT a good idea. You can destrcuture all the properties you need and flatten them in that order:

input.flatMap(({ key1, key2,  key3 }) => [key1, key2, key3])

or

Create an array of keys to make it a bit more dynamic:

const keys = ["key1", "key2", "key3"]
const output = input.flatMap(o => keys.map(k => o[k]))
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