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

阿马尔·阿兰

我有一个对象数组:

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

我搜索了它,但我无法找到如何以我想要的方式获得它。

黑胡子

恕我直言,你正在寻找这样的使用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})));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章