【问题标题】:Object Filter Using JS [duplicate]使用 JS 的对象过滤器 [重复]
【发布时间】:2021-07-14 10:14:09
【问题描述】:

我正在尝试使用 JavaScript 从对象中过滤选定的属性。

这是我的数组

const odata=[
  {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
  },
  {
    "id": "0002",
    "type": "ansd",
    "name": "EARK",
    "ppu": 0.67,
  }
];

我想要这样的输出 - 我只想从对象中选择 2 个 (id,type) 道具

[
  {"id": "0001","type": "donut"}
  {"id": "0002","type": "ansd"}
]

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    我们可以使用Array.map 和一些Destructuring 来获得想要的结果。

    解构赋值语法允许我们以方便的方式从对象和数组中获取选定的值。

    const odata= [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, }, { "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67, } ];
    
    const result = odata.map(({ id, type}) => ({ id, type }));
    console.log("Result:", result)

    【讨论】:

    【解决方案2】:

    用户Array.prototype.map() 从现有数组生成新数组。

    Reference

    const odata = [
      { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 },
      { "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67 }
    ];
    const output = odata.map(node => ({
        id: node.id,
        type: node.type,
    }))
    console.log(output)

    【讨论】:

      猜你喜欢
      • 2023-01-02
      • 2019-06-05
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多