简体   繁体   English

获取具有非空数组作为值的属性的 object 键

[英]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.entriesfilter

 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.

相关问题 错误:“输入”过滤器需要非空数组 - Error: A non-empty array is required for 'in' filters 如何在 typescript 中键入非空数组? - How to type a non-empty array in typescript? Angular 8 迭代非空数组的问题 - Problem in Angular 8 iterating non-empty array 为什么非空数组的长度为0 - Why is the length of a non-empty array is 0 键必须是非空字符串,并且不能包含“.”、“#”、“$”、“/”、“[”或“]” - Keys must be non-empty strings and can't contain “.”, “#”, “$”, “/”, “[”, or “]” Object.keys返回包含属性的对象的空数组 - Object.keys returns an empty array for an object containing properties ESLint 7.1.0 错误:“模式”必须是非空字符串或非空字符串数组 - ESLint 7.1.0 Error: 'patterns' must be a non-empty string or an array of non-empty strings Firebase错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组 - Firebase Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array FormData对象即使对于非空表单也返回空 - FormData object returns empty even for a non-empty form 仅更新非空字段| 对象传播 - Update only non-empty fields | Object spread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM