Reputation: 12561
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. Please also consider effort in my (self-)answer.
let pendingAdditions = {
hospitals: ['Silencio Hospital','St Judes'],
licenses: ['poe-tic license'],
medschools: []
}
Upvotes: 0
Views: 91
Reputation: 11011
How about Object.values
with flat
and includes
.
// 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'));
Upvotes: 2
Reputation: 12561
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; in the case of passing null
an error results.
Upvotes: 3