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;
Share:
14,657
user1722366
Author by

user1722366

Updated on June 13, 2022

Comments

  • user1722366
    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
    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
    mehulmpt almost 5 years
    @TylerRoper thanks for the hint! or I could flatten the array using flat
  • Tyler Roper
    Tyler Roper almost 5 years
    You can, although you're using an additional iteration (map -> flat) as opposed to a single flatMap. Not sure what the efficiency difference would be though so it may be negligible.
  • David Fontes
    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
    nice_dev almost 5 years
    @DavidFontes Ahh!! Overlooked that.