我有一个采用以下格式的数据集:
{
roof: 'black',
door: 'white',
windows: 8
},
{
roof: 'red',
door: 'green',
windows: 2
},
{
roof: 'black',
door: 'green',
windows: 8
}
我想从每个对象中删除roof: 'black'
,door: 'green'
和windows: 2
中的每个键/值对。我所做的是以下事情:
if (object.roof == 'black'){
delete object.roof;
}
if (object.windows == 2){
delete object.windows;
}
if (object.door == 'green'){
delete object.door;
}
但是感觉有点难看。还有其他更好的方法吗?
答案 0 :(得分:0)
您可以将一个对象作为键值/对,并通过事先检查删除属性。
var array = [{ roof: 'black', door: 'white', windows: 8 }, { roof: 'red', door: 'green', windows: 2 }, { roof: 'black', door: 'green', windows: 8 }],
remove = { roof: 'black', windows: 2, door: 'green' };
array.forEach(o =>
Object.entries(remove).forEach(([k, v]) =>
o[k] === v && Reflect.deleteProperty(o, k)));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }