Beginner
Beginner

Reputation: 9135

Merging multiple arrays inside a array of objects into a single array

I have a object where data is an array of objects, inside data object I have one users property which is an array.

I need to get all the users into a single array. I have written using map and concat.

Is there any way I can have a better solution, or this is correct?

See the below snippet.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

var users = response.data.map(o => o.users)

const usersCollection = [].concat(...users)

console.log(usersCollection)

Upvotes: 4

Views: 12664

Answers (5)

Mamun
Mamun

Reputation: 68933

You can use Array.prototype.flat():

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth | Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

var users = response.data.map(o => o.users).flat();

console.log(users);

You can also try with Array.prototype.flatMap() which is identical to a map followed by a call to flat of depth 1.

var users = response.data.flatMap(o => o.users);

Upvotes: 17

aniket mule
aniket mule

Reputation: 91

You can use ES6 spread operator

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}    
var NEWARRAY = [];
for(var v of response.data){
  NEWARRAY.push(...v.users);
}
console.log(NEWARRAY);

Upvotes: 0

cantuket
cantuket

Reputation: 1592

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient

response.data.flatMap(({users})=>users)

You should be careful with vendor support though if you’re running in the browser.

Upvotes: 0

Bathri Nathan
Bathri Nathan

Reputation: 1267

Using ES6 Spread operator you can do the job quick.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

let wantedArray = [];
for(let v of response.data){
  wantedArray.push(...v.users);
}

console.clear();
console.log(wantedArray);

Upvotes: 0

CRayen
CRayen

Reputation: 579

If Using ES6, utilizing the power of spread with Array.reduce

var response = {
  data: [{
    users: [1, 2, 3]
  }, {
    users: [4, 5, 6]
  }]
}

var users = response.data.reduce((accumulator, obj) => [...accumulator, ...obj.users], []);

console.log(users);

Upvotes: 0

Related Questions