javascript - 如何过滤数组中对象的属性
问题描述
我有一个对象数组:
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})));
推荐阅读
- tensorflow - 如何约束深度神经网络的输出
- arrays - 迭代 api 响应 Ruby on Rails - 带有哈希的数组
- php - 循环遍历 PHP 中的数组
- express - 在 API 上使用 get 时出错(Vue.js、express.js)
- amazon-dynamodb - DynamoDB 忽略了索引的使用
- ios - 呈现 UIAlertController 时 iOS 应用程序崩溃
- javascript - 如何将 Decimal128 值转换为 JavaScript 中的数字?
- jpa - EJB 方法被多次调用
- python - 如何根据另一列的条件/分组删除一列中连续的重复行?
- scala - 从 play 2.1 迁移到 2.6 后上传文件不再起作用