-2

INPUT

[0]: [{}, {}],
[1]: [{}, {}],
[2]: [{}]

I have index 0, 1 and 2 with array of objects. Now I need to merge all these index values into a single array of object

Expected O/P

[{}, {}, {}, {}, {}]

2

3 Answers 3

1

let arr = [
  [{
    key1: "value1"
  }, {
    key2: "value2"
  }],
  [{
    key3: "value3"
  }, {
    key4: "value4"
  }],
  [{
    key5: "value5"
  }]
];

arr = arr.flat();

console.log(arr);

Sign up to request clarification or add additional context in comments.

Comments

-1

Here's just one solution like you need:

let a = {
  0: [{}, {}],
  1: [{}, {}],
  2: [{}]
}

let values = []
for (var x in a)
{
    a[x].map(p => values.push(p))
}
console.log(values)  //[{}, {}, {}, {}, {}]

Make sure to handle each case, validate if it's an array then loop over it.

Comments

-1

You can do a one liner using the reduce:

const obj = {
  0: [{}, {}],
  1: [{}, {}],
  2: [{}]
}

const arr = Object.values(obj).reduce((acc, curr) => ([...acc, ...curr]), [])
console.log(arr)

Comments

Your Answer

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.