从键值是空数组的JS对象中删除 [英] Remove from JS object where key value is an empty array
本文介绍了从键值是空数组的JS对象中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从值为Array(0)的对象中删除键.这是对象:
I'm trying to remove keys from an object where the values is Array(0). Here's the object:
{fruit: Array(1), dairy: Array(2), vegetables: Array(0)}
这是理想的结果:
{fruit: Array(1), dairy: Array(2)}
到目前为止,我一直在使用delete运算符和.filter/.reduce方法.
So far, I've been playing with the delete operator and .filter/.reduce methods.
任何帮助都会很棒:)
推荐答案
只需遍历对象的键,检查该键的值是否为空数组,如果是,则将其删除:
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);
这篇关于从键值是空数组的JS对象中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文