简体   繁体   English

如何确定对象中的任何数组是否有条目

[英]How to determine if any arrays in an object has an entry

This is unlike most questions, which concern arrays of objects, not objects of arrays.这与大多数问题不同,后者涉及对象数组,而不是数组对象。 I have a data structure such as the following, and I need to determine if any of the arrays contained by the object contain any values.我有一个如下所示的数据结构,我需要确定对象包含的任何数组是否包含任何值。

All I need is true/false if any of the arrays has at least one value.如果任何数组至少有一个值,我只需要 true/false。 Please also consider effort in my (self-)answer.还请考虑在我(自我)回答中的努力。

let pendingAdditions = {
  hospitals: ['Silencio Hospital','St Judes'],
  licenses: ['poe-tic license'],
  medschools: []
} 

I found nothing upon googling, maybe that is because the answer is as simple as:我在谷歌上一无所获,也许是因为答案很简单:

let somePendingAdditions = Object.values(pendingAdditions).some(arr => arr.length);

However there is an alternative solution which is probably not as performant but also has interesting pitfalls possibly worth noting:然而,有一个替代解决方案可能不是那么高效,但也有可能值得注意的有趣陷阱:

somePendingAdditions = 
    Boolean(Array.prototype.concat.apply([], Object.values(pendingAdditions)).length);

The pitfall(s) have to do with passing the correct first argument to apply.陷阱与传递正确的第一个参数有关。 Ordinarily this is done with {} or null , but in the first case {} will be an entry in the resulting array;通常这是用{}null ,但在第一种情况下{}将是结果数组中的一个条目; in the case of passing null an error results.在传递null的情况下会导致错误。

How about Object.values with flat and includes . Object.valuesflatincludes怎么样。

 // Check if Object has value as arrays and atleast one value is there. const hasAnyEntry = (items) => Object.values(items).flat().length > 0; const pendingAdditions = { hospitals: ['Silencio Hospital','St Judes'], licenses: ['poe-tic license'], medschools: [] } console.log(hasAnyEntry(pendingAdditions)); console.log(hasAnyEntry({})); // Check if given entry is exist in Object value arrays const hasEntry = (items, entry) => Object.values(items).flat().includes(entry); console.log(hasEntry(pendingAdditions, 'St Judes')); console.log(hasEntry(pendingAdditions, 'Blah'));

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

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