【问题标题】:How to filter properties of an object in an array [duplicate]如何过滤数组中对象的属性[重复]
【发布时间】:2019-01-03 08:20:33
【问题描述】:

我有一个对象数组:

const ObjArray= [{
            "id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
            "name": "john",
            "description": "worker",
            "place": "f.1.1",
            ...
},
{
            "id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
            "name": "joe",
            "description": "dev",
            "stepType": "d.2.1",
            ...
}
];

我想过滤上面的对象数组,只返回对象的特定属性。
假设我只想返回一个新数组中每个对象的 id 和名称,如下所示:

[{
  "id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
  "name": "john"},
 {
  "id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
  "name": "joe" }

我对此进行了搜索,但找不到我想要的方式。

【问题讨论】:

  • “提前致谢”:对不起,您应该先研究和尝试。 idownvotedbecau.se/noattempt 仅仅说“我搜索了但找不到” 是不够的,因为 StackOverflow 有很多类似的问题和答案。
  • 你有什么尝试吗?
  • 使用Array#map
  • 我试过 map(a => a.id) 但它似乎只适用于单个属性并返回一个对象中的所有 id
  • 试试 map(a=>({id:a.id, name: a.name})) 然后

标签: javascript json


【解决方案1】:

恕我直言,您正在使用Array#map 寻找类似的东西:

ObjArray= [{
            "id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
            "name": "john",
            "description": "worker",
            "place": "f.1.1"  },
{
            "id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
            "name": "joe",
            "description": "dev",
            "stepType": "d.2.1",}
];

console.log(ObjArray.map(o => ({'id': o['id'], 'name': o['name']})));

如果你喜欢object destructuring

ObjArray= [{
            "id": "90e17e10-8f19-4580-98a8-ad05f4ecd988",
            "name": "john",
            "description": "worker",
            "place": "f.1.1"  },
{
            "id": "90e17e10-8eqw-4sdagfr4ecd9fsdfs",
            "name": "joe",
            "description": "dev",
            "stepType": "d.2.1",}
];

console.log(ObjArray.map(({id, name}) => ({id, name})));

【讨论】:

  • 我按我的意愿工作,我很感激它
猜你喜欢
  • 1970-01-01
  • 2016-05-15
  • 2018-05-25
  • 2019-08-22
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2021-03-20
  • 2021-04-15
相关资源
最近更新 更多