So I have a structure like that:
Foo: {
A: Array[0],
B: Array[0],
C: Array[1]
}
where [X]
is length of the array, but Foo
is an object, not an Array, therefore I can't use Array method on it.
How do I get first element (letter in this case) which has length > 0
?
for (let letter in Foo) {
if (letter.length > 0) {
let match = letter;
}
}
I tried something like this (this is simplified version), but it just returns all properties of Foo
.
I'm glad you're using ES6. In this case you can use Object.keys
to get an array of all the object's keys and Array.prototype.find
to find the first element with a specific property:
var obj = {
a: [],
b: [],
c: [
2,
3
],
d: [],
e: [
1
]
};
Object.keys(obj).find(a => obj[a].length > 0); // The letter "c" which contains the first non-empty array.
obj[Object.keys(obj).find(a => obj[a].length > 0)]; // Array [2, 3] itself
Note that there's no consistent “first” element in an object across implementations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.