-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

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

Sundar
  • 155
  • 1
  • 1
  • 5
  • 3
    use [flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – DecPK Sep 09 '21 at 04:05
  • Duplicate of [Converting an array of single object arrays, to an array of objects](/q/63344699/4642212). Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 09 '21 at 05:49

3 Answers3

1

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

arr = arr.flat();

console.log(arr);
Vineet Desai
  • 872
  • 5
  • 16
-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.

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
-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)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
Karma Blackshaw
  • 880
  • 8
  • 20