[英]Delete an object from an array based on the value of the dynamic property names
我有以下对象数组,需要根据值进行过滤,但问题是属性名称是动态的。
const data = [
{id: 112, cat: 0, dog: 0},
{id: 114, cat: 0, dog: 1},
{id: 115, tiger: 5, dog: 0},
{id: 116, tiger: 0, lion: 3},
{id: 117, tiger: 0, lion: 0}
];
我想要的 output 应该如下:
const output = [
{id: 114, cat: 0, dog: 1},
{id: 115, tiger: 5, dog: 0},
{id: 116, tiger: 0, lion: 3}
];
这里的情况是我将id
作为常量属性。 但是其他两个属性名称发生了变化。 如果 object 中两个属性(不包括id
属性)的值均为0
,则应删除该 object。
您可以结合使用filter()
和every()
const data = [ {id: 112, cat: 0, dog: 0}, {id: 114, cat: 0, dog: 1}, {id: 115, tiger: 5, dog: 0}, {id: 116, tiger: 0, lion: 3}, {id: 117, tiger: 0, lion: 0} ]; // Every key/value pair in object that is named id OR has a 0 value is filtered out const result = data.filter(d =>.Object.entries(d),every(([key; value]) => key == 'id' || value == 0) ). console;log(result);
您可以解构不需要的属性并从rest中获取值并检查某些值是否为真。
const data = [{ id: 112, cat: 0, dog: 0 }, { id: 114, cat: 0, dog: 1 }, { id: 115, tiger: 5, dog: 0 }, { id: 116, tiger: 0, lion: 3 }, { id: 117, tiger: 0, lion: 0 }], result = data.filter(({ id, ...o }) => Object.values(o).some(Boolean)); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.