仅从数组中的每个对象中提取某些属性,然后添加到新数组中

时间:2019-10-10 14:51:08

标签: javascript arrays object foreach array.prototype.map

尝试学习javascript。我正在尝试根据状态数据(通过Context API发送到组件)创建表行数据:

myArr = [
   {id: 1, name: AA, desc: DescA, color: red},
   {id: 2, name: BB, desc: DescB, color: orange},
   {id: 3, name: CC, desc: DescC, color: green},
   {id: 4, name: DD, desc: DescD, color: blue},
]

我只想从每个对象中提取名称和颜色,并创建一个新的对象。

newArr = [
   {name: AA, color: red}
   {name: BB, color: orange}
   {name: CC, color: green}
   {name: DD, color: blue}
]

我想这样做以将表数据与表标题匹配:

const headCells = [
    { id: 'name', numeric: false, disablePadding: true, label: 'Name' },
    { id: 'color', numeric: false, disablePadding: false, label: 'Color' },
];

我尝试过.mapArray.prototype.forEach(),但是我使用它们的方式不正确:

var newArray = activities.map(function(item) {return item["name", "color"]; })

对此道歉几乎可以肯定是重复的。任何帮助将非常感激。谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.map创建一个新数组:

const newArray = myArray.map(item => ({ name: item.name, color: item.color }));

或者,采用解构分配(ES6):

const newArray = myArray.map(({ item, color }) => ({ item, color }));

答案 1 :(得分:1)

如果您想从id获取headCells,则可以提前获取密钥并映射属性。

var data = [{ id: 1, name: 'AA', desc: 'DescA', color: 'red' }, { id: 2, name: 'BB', desc: 'DescB', color: 'orange' }, { id: 3, name: 'CC', desc: 'DescC', color: 'green' }, { id: 4, name: 'DD', desc: 'DescD', color: 'blue' }],
    headCells = [{ id: 'name', numeric: false, disablePadding: true, label: 'Name' }, { id: 'color', numeric: false, disablePadding: false, label: 'Description' }],
    keys = headCells.map(({ id }) => id),
    result = data.map(o => Object.assign({}, ...keys.map(k => ({ [k]: o[k] }))));

console.log(result);

使用更新的Object.fromEntries

var data = [{ id: 1, name: 'AA', desc: 'DescA', color: 'red' }, { id: 2, name: 'BB', desc: 'DescB', color: 'orange' }, { id: 3, name: 'CC', desc: 'DescC', color: 'green' }, { id: 4, name: 'DD', desc: 'DescD', color: 'blue' }],
    headCells = [{ id: 'name', numeric: false, disablePadding: true, label: 'Name' }, { id: 'color', numeric: false, disablePadding: false, label: 'Description' }],
    keys = headCells.map(({ id }) => id),
    result = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);