【问题标题】:Pull only certain properties from each object in an array, and add to new array仅从数组中的每个对象中提取某些属性,并添加到新数组中
【发布时间】:2020-02-08 01:31:54
【问题描述】:

尝试学习 javascript。我正在尝试从状态数据创建表格行数据(通过上下文 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},
]

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

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"]; })

抱歉,这几乎可以肯定是重复的。任何帮助将非常感激。谢谢!

【问题讨论】:

  • 你如何从desccolor
  • @NinaScholz 哎呀 - 已编辑!谢谢
  • .map 是正确的方法,您的语法略有错误。 return { name: item.name, color: item.color }

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    或者,使用解构赋值(ES6):

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

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2023-02-09
      • 2019-09-02
      • 2014-08-17
      • 2016-11-27
      • 2019-04-16
      相关资源
      最近更新 更多