如何将对象数组解构为其键的多个数组?

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

我的数据集是一个对象数组,它们都只有两个键(idname):

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

我想以这样的方式解构它们,最终分别得到一个 ID 数组和一个名称数组:

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

我是这样做的,但我认为通过解构可以做得更好:

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)

您可以使用

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

获取数组

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)

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;
}