1

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?

2

1 Answer 1

6

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.