首页 > 解决方案 > 如何过滤数组中对象的属性

问题描述

我有一个对象数组:

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" }

我对此进行了搜索,但找不到如何以我想要的方式获得它。

标签: javascriptjson

解决方案


恕我直言,您正在寻找这样的东西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})));


推荐阅读