-1

I'm trying to figure out how to get a key from an Any type in Angular/Typescript.

For example, if some other part of the program is returning this code:

{
  Amy: {
         age: 7,
         grade: 2
       },
  Max: {
         age: 9,
         grade: 4
       },
  Mia: {
         age: 8,
         grade: 3
       }
}

Is there a way that I can put the names in an array such as:

[ "Amy", "Max", "Mia" ]

I've tried to use forEach, but the first bit of code isn't exactly an array so I'm not sure if that is on the right track at all. Is there some sort of function I can use to turn Amy into a string? Any help would be appreciated. Thanks!

R. Richards
  • 24,603
  • 10
  • 64
  • 64

2 Answers2

1

You can use Object.keys()

let obj = {
  Amy: {
         age: 7,
         grade: 2
       },
  Max: {
         age: 9,
         grade: 4
       },
  Mia: {
         age: 8,
         grade: 3
       }
}
console.log(Object.keys(obj));
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

You don't actually have to use anything from Angular for this you can use plain JavaScript functionality. Just grab the keys from the object with Object.keys

const myObject:any = {
  Amy: {
         age: 7,
         grade: 2
       },
  Max: {
         age: 9,
         grade: 4
       },
  Mia: {
         age: 8,
         grade: 3
       }
}
const names:Array<string> = Object.keys(myObject);
console.log(names);
zmanc
  • 5,201
  • 12
  • 45
  • 90