仅从数组中的每个对象中提取某些属性,然后添加到新数组中 [英] Pull only certain properties from each object in an array, and add to new array

查看:82
本文介绍了仅从数组中的每个对象中提取某些属性,然后添加到新数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Attempting to learn javascript. I am trying to create Table Row data from data in state (being sent to components via 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},
]

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

I would like to pull only name and color from each object, and create a new arr of objects.

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

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

I would like to do this to match my table data to table headers:

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

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

I have tried .map and Array.prototype.forEach(), but I am using them incorrectly:

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

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

Apologies for this almost certainly being a duplicate. Any help would be really appreciated. Thanks!

推荐答案

您可以使用

You can use Array.prototype.map to create a new array:

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

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

Or, with destructuring assignement (ES6):

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

这篇关于仅从数组中的每个对象中提取某些属性,然后添加到新数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆