How to destructure an array of objects into multiple arrays of its keys? [duplicate]

  arrays, javascript, object-destructuring

My data set is an array of objects which all have only two keys (id and name):

[{ id: 1, name: 'Foo'}, { id: 2, name: 'Bar'}, { id: 3, name: 'FooBar'}, { id: 4, name: 'BarFoo'}]

I want to destructure them in such a way that I end up having an id-array and a name-array respectively:

[1, 2, 3, 4] // ids
['Foo', 'Bar', 'FooBar', 'BarFoo'] // name

I did it this way but I think it can probably be done better with destructering:

const data = [{ id: 1, name: 'Foo'}, { id: 2, name: 'Bar'}, { id: 3, name: 'FooBar'}, { id: 4, name: 'BarFoo'}]

let ids = []
let names = []
data.forEach(obj => {
  ids.push(obj.id)
  names.push(obj.name)  
})

console.log(ids)
console.log(names)

Source: Ask Javascript Questions

LEAVE A COMMENT