0

How to get the values of key value pairs defined in an interface in typescript -

interface Person {
    [Id: string]: PersonConfig
}

interface PersonConfig {
    name: string,
    age: number
}

const people: Person[] = [
    {
      "p1": {
          name: "abcd",
          age: 20
      }
    },
    {
      "p2": {
          name: "efgh",
          age: 78
      }
    }
];

Object.entries(people).forEach(([key, value]) => {
  console.log(value);
});

I get the result as -

{ p1: { name: 'abcd', age: 20 } }
{ p2: { name: 'efgh', age: 78 } }

Now, I want the values of key and values separately. I do not see a way other than providing key values by myself (console.log(value["p1"])).

Expecting the output as :

console.log(value.Id + "-" + value.PersonConfig);
MeghanaO
  • 37
  • 3
  • 6
  • Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – imvain2 Jun 01 '20 at 20:04
  • Why is `people` an array? Try logging the `key` in your loop to understand what's going on. – Bergi Jun 01 '20 at 20:04

1 Answers1

0

You don't need to use Object.entries in an array. It is used for objects. Since your people is an array you can use normal forEach like below.

people.forEach(person => {
  Object.entries(person).forEach(([key, value]) => {
    console.log(key, value);
  });
});
Thusitha
  • 3,393
  • 3
  • 21
  • 33