如何过滤数组中对象的属性

时间:2018-07-26 10:52:27

标签: javascript json

我有一个对象数组:

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

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

1 个答案:

答案 0 :(得分:3)

恕我直言,您正在使用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})));