how to get value if the object key is dynamic in typescript?
14,657
Solution 1
If you are sure that each object within the array as 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
}
Solution 2
This will give you an array of objects with the contents of each animal.
animals.map(animal => animal[Object.keys(animal)[0]]);
Solution 3
1) Find an animal with that key
2) Return it with [animal]
3) Use it as you would (.leg
)
const animals = [{ cow: { leg: 4, eye: 2 } }, { monkey: { leg: 2, eye: 2 } }];
const animal = 'cow';
const leg = animals.find(a => !!a[animal])[animal].leg;
Author by
user1722366
Updated on June 13, 2022Comments
-
user1722366 almost 2 years
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
-
David Fontes almost 5 years@TylerRoper Thank you, I made it as an inline snippet as you suggested. Also, with the array supplied it works, however I will try to come up with a better solution.
-
mehulmpt almost 5 years@TylerRoper thanks for the hint! or I could flatten the array using
flat
-
Tyler Roper almost 5 yearsYou can, although you're using an additional iteration (
map
->flat
) as opposed to a singleflatMap
. Not sure what the efficiency difference would be though so it may be negligible. -
David Fontes almost 5 years@vivek_23 I'm not iterating over the array with
Object.keys()
, I'm only using it to get the keys of each animal. -
nice_dev almost 5 years@DavidFontes Ahh!! Overlooked that.