简体   繁体   English

从JS对象中删除键值为空数组

[英]Remove from JS object where key value is an empty array

I'm trying to remove keys from an object where the values is Array(0). 我正在尝试从值为Array(0)的对象中删除键。 Here's the object: 这是对象:

{fruit: Array(1), dairy: Array(2), vegetables: Array(0)}

This is the desired result: 这是期望的结果:

{fruit: Array(1), dairy: Array(2)}

So far, I've been playing with the delete operator and .filter/.reduce methods. 到目前为止,我一直在使用delete运算符和.filter / .reduce方法。

Any help would be awesome :) 任何帮助都是极好的 :)

Just iterate over the keys of the object, check if the value for that key is an empty array and if so, delete it: 只需迭代对象的键,检查该键的值是否为空数组,如果是,则删除它:

 let obj = { a: [1], b: [], c: 5, d: false } for (const key in obj) { if (Array.isArray(obj[key]) && !obj[key].length) delete obj[key] }; console.log(obj); 

The filter/reduce operators are for Arrays not for objects. filter / reduce运算符用于Arrays而不是对象。 If you must use the filter/reduce operators, you can try: 如果必须使用filter / reduce运算符,可以尝试:

 const obj = {a: [1], b: [1,2], c: []}; const filtered = Object.keys(obj) .filter(key => Array.isArray(obj[key]) && obj[key].length != 0) .reduce((acc, key) => {acc[key] = obj[key]; return acc}, {}); console.log(filtered); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM