Pull only certain properties from each object in an array, and add to new array

眉间皱痕 提交于 2021-01-29 11:55:48

问题


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' },
];

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!


回答1:


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

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

Or, with destructuring assignement (ES6):

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



回答2:


If you like to get the id from headCells, you could get the keys in advance and map the properties.

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

Approach with newer 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);


来源:https://stackoverflow.com/questions/58325707/pull-only-certain-properties-from-each-object-in-an-array-and-add-to-new-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!