[英]Get object keys for properties having non-empty array as a value
I have an array:我有一个数组:
417: Array(2)
0: 24301
1: 24300
length: 2
__proto__: Array(0)
418: [24562]
length: 419
__proto__: Array(0)
Now, i need to get all those keys from this array arr
whose length is greater than 0. In this case, i need the answer as ['417','418']
.现在,我需要从这个数组
arr
中获取所有长度大于 0 的键。在这种情况下,我需要答案为['417','418']
。
I have tried to filter using each
loop and .length
of each element as:我尝试使用
each
循环和每个元素的.length
进行过滤:
My code is as:我的代码如下:
console.log(arr_of_sel_units);
$.each(arr_of_sel_units, function(k, v) {
console.log(v.length)
});
But, it is returning error Cannot read property 'length' of undefined
但是,它返回错误
Cannot read property 'length' of undefined
If proper datatype ( Object
) used for arr
, you may do Array.prototype.filter()
across Object.keys()
(however, it will work for your notation just as well as array is essentially an object):如果正确的数据类型(
Object
)用于arr
,您可以在Object.keys()
中执行Array.prototype.filter()
) (但是,它适用于您的符号,就像数组本质上是一个对象一样):
const src = {a: ['1','2','3' ], b: [], c: ['1' ], d: []}, result = Object.keys(src).filter(key => src[key].length) console.log(result)
Use Object.entries
, filter
使用
Object.entries
, filter
let arr = []; arr["a"] = ["1", "2", "3"]; arr["b"] = []; arr["c"] = ["1"]; arr["d"] = []; const res = Object.entries(arr).filter(([, value]) => value.length > 0).map(([key]) => key); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.