检查多个对象属性的值并将其删除

时间:2018-08-02 10:14:15

标签: javascript node.js

我有一个采用以下格式的数据集:

{
  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;
}

但是感觉有点难看。还有其他更好的方法吗?

1 个答案:

答案 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; }