2

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)
leonheess
  • 16,068
  • 14
  • 77
  • 112
  • 1
    May be you can do `data.forEach(({id, name}) => { ids.push(id); names.push(name); })`. – Nithish Feb 23 '21 at 09:28
  • Destructuring can't help you here since you have a dynamic number of elements. Because destructuring involves declaring variables it cannot be dynamic. – Felix Kling Feb 23 '21 at 09:42

3 Answers3

9

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

const {ids, names} = {ids: arr.map(a => a.id), names: arr.map(a => a.name)}

console.log(ids)
console.log(names)
leonheess
  • 16,068
  • 14
  • 77
  • 112
3

You can use

data.map(x => x.id)
data.map(x => x.name)

to get arrays

Luke
  • 126
  • 8
1

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

const formatData = (data) => {
  return data.reduce((res, { id, name }) => {
    res.ids.push(id);
    res.names.push(name);
    return res;
  }, { ids: [], names: [] })
}

const {ids, names} = formatData(data);

console.log("ids: ", ids);
console.log("names: ", names);
.as-console-wrapper {
  max-height: 100% !important;
}

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

const ids = data.map(({ id }) => id );
const names = data.map(({ name }) => name );

console.log("ids: ", ids);
console.log("names: ", names);
.as-console-wrapper {
  max-height: 100% !important;
}
Nithish
  • 5,393
  • 2
  • 9
  • 24