I have an array of object.structure is like that.
animal = [{"cow":{"leg":4,"eye":2}},{"monkey":{"leg":2,"eye":2}}]
here first key is dynamic like cow and monkey
so my question is how can i access the key leg if first key is dynamic
If you are sure that each object within the array has only 1 property (which would be the type of animal), you can do something like this.
animals = [{"cow":{"leg":4,"eye":2}},{"monkey":{"leg":2,"eye":2}}];
for (let animal of animals) {
let propName = Object.keys(animal)[0];
let result = animal[propName];
console.log(result); // <- Do what you want with it
}
You can use the newly added Object.entries
, which make the most sense imo.
Thus for your data you have:
const animal = ...
for (a of animal) {
const [animalName, animalDesc] = Object.entries(a)[0]; // assumes there is only one
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With