How can I find out if a Javascript Object that has a property with an array has been defined?
x = {};
x.gp = [];
x.gp[0] = {};
x.gp[0].jockey = 14;
// Find if the first array within the Object x i.e, x.gp[0] exists NOT just x.gp
Thanks in advance.
2
Answers
I am unsure what you mean with "the first array within the Object". Do you mean the first property that has been set in the object or the first property listed by the [[OwnPropertyKeys]] enumerable ?
If you just mean "how to know if the object has at least one property whose value is an array", you can do something like this :
Basically, we get all the property values with
Object.values
, and then we run a predicate function withArray.some
, and finally we useArray.isArray
as the predicate to check if at least one of those values is an array.It’s not 100% clear what do you want but given
xp[0] exists
, that means you want to check whether an object contains a non-empty array. So:If you need some fast code, use an imperative option:
And a benchmark: