我想从数组中的对象中删除每个属性,除了其中一些属性:
var listToKeep = ['name', 'school'];
var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
{id:'efg',name:'em', school: 'b', sport: 's'},
{id:'hij',name:'ge', school: 'c', sport: 'n'}]
我正在尝试这个,但这只是试图删除一个:
arrayOfObjects .forEach(function(v){ delete v.id});
预期结果将是:
var arrayOfObjects = [{name:'oh', school: 'a'},
{name:'em', school: 'b'},
{name:'ge', school: 'c'}]
我不想使用for loop
。
答案 0 :(得分:2)
您可以将数组中的每个项目映射到新项目,通过减少要保留的键列表来创建:
const newArray = arrayOfObjects.map(obj => listToKeep.reduce((newObj, key) => {
newObj[key] = obj[key]
return newObj
}, {}))
如果要改变原始对象并删除属性,可以使用两个forEach循环并删除运算符:
arrayOfObjects.forEach(obj => listToKeep.forEach((key) => {
delete obj[key]
}, {}))
如果你可以使用lodash或类似的库,你可以选择对象的属性,例如:
const newArray = arrayOfObjects.map(obj => _.pick(obj, listToKeep))
答案 1 :(得分:2)
您可以遍历arrayOfObjects
数组中每个JSON对象的键,然后如果在数组listToKeep
中找不到该键,则从该对象中删除该key:value
。由于您要更改现有的arrayOfObjects
,因此您可以按照此方法在对象属性上使用delete
。
var listToKeep = ['name', 'school'];
var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
{id:'efg',name:'em', school: 'b', sport: 's'},
{id:'hij',name:'ge', school: 'c', sport:'n'}];
arrayOfObjects.forEach((obj)=>{
Object.keys(obj).forEach((key)=>{
if(listToKeep.indexOf(key) === -1){
delete obj[key];
}
});
});
console.log(arrayOfObjects);