在我的情况下,是否有一种简单的方法仅返回几个键,例如,我只想返回标题名称,字段和类型(如果存在)。我知道我可以通过
删除密钥for (i = 0; i < obj.length; i++) {
delete obj[i]['type']
delete obj[i]['hide']
delete obj[i]['position']
}
这意味着我将不得不遍历数组中的所有文档并删除键,但不确定是否有更简单的更快方法来实现。就我而言,该文档永远不会庞大,因为它仅存储列定义以导出数据
[ {
"headerName": "assessed_combined_value",
"field": "assessed_combined_value",
"hide": false,
"position": 8,
"type": "money"
},
{
"headerName": "assessee1",
"field": "assessee1",
"hide": false,
"position": 1
},
{
"headerName": "assessee2",
"field": "assessee2",
"hide": false,
"position": 2
},
{
"headerName": "bathrooms",
"field": "bathrooms",
"hide": false,
"position": 5
}
]
答案 0 :(得分:3)
您可以使用解构
let data = [{"headerName": "assessed_combined_value","field": "assessed_combined_value","hide": false,"position": 8,"type": "money"},{"headerName": "assessee1","field": "assessee1","hide": false,"position": 1},{"headerName": "assessee2","field": "assessee2","hide": false,"position": 2},{"headerName": "bathrooms","field": "bathrooms","hide": false,"position": 5}]
let final = data.map(({field, headerName}) => ({headerName, field}))
console.log(final)
如果情况相反,您只想保留一些属性,并选择所有其他属性,则可以使用spread syntax
,即,如果您只想保留field
键>
let final = data.map(({field, ...rest}) => rest)
答案 1 :(得分:0)
您可以将传播运算符与先前发布的答案结合使用,以仅显示当前迭代对象中存在的那些字段。
let info = [{
"headerName": "assessed_combined_value",
"field": "assessed_combined_value",
"hide": false,
"position": 8,
"type": "money"
},
{
"headerName": "assessee1",
"field": "assessee1",
"hide": false,
"position": 1
},
{
"headerName": "assessee2",
"field": "assessee2",
"hide": false,
"position": 2
},
{
"headerName": "bathrooms",
"field": "bathrooms",
"hide": false,
"position": 5
}]
const result = info.map(({field, headerName, type}) => ({
...(headerName && {"headerName": headerName}),
...(field && {"field": field}),
...(type && {"type": type})
}));
console.log(result);