Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get value if the object key is dynamic in typescript?

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

like image 204
user1722366 Avatar asked Jan 26 '23 01:01

user1722366


2 Answers

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
}
like image 91
David Fontes Avatar answered Jan 28 '23 15:01

David Fontes


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
}
like image 36
adz5A Avatar answered Jan 28 '23 14:01

adz5A