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
}
Object.keys(), I'm only using it to get the keys of each animal.Maybe convert it into a "non-dynamic-key" object?
const animal = [{"cow":{"leg":4,"eye":2}},{"monkey":{"leg":2,"eye":2}}]
const newanimal = animal.map(obj => {
const keys = Object.keys(obj)
return keys.map(key => ({ key, value: obj[key] }))
}).flat(Math.Infinity)
console.log(newanimal)
flatmap -> flat) as opposed to a single flatMap. Not sure what the efficiency difference would be though so it may be negligible.You can use map & Object.keys. map will return a new array. Object.keys is use to get all the keys inside each of the object in animal array.Then this line elem[getKeys].leg will retrieve the value of the leg key
let animal = [{
"cow": {
"leg": 4,
"eye": 2
}
}, {
"monkey": {
"leg": 2,
"eye": 2
}
}];
let legVal = animal.map((elem) => {
let getKeys = Object.keys(elem)[0];
return elem[getKeys].leg
})
console.log(legVal)
Object.keys()and, for each one, check if the key's value containsleg. Or, if it will only ever be one key, no need to loop; you can just doObject.keys(obj)[0]to get the first key. Or, better yet, if you don't actually need the key name and just want to know iflegexists, useObject.values(obj)[0].leg.