简体   繁体   中英

Loop through Key value pairs in Typescript

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);

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);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM