1

I added an array of keyvalue for months.

  months : { [key: number]: string } = { 1: 'January', 2: 'February', 3: 'March', 
  4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October',
  11: 'November', 12: 'December' } 

I can get the value without any issues

var firstMonth= this.months[0].valueOf();

However, I can't get the key value.

I tried this.months[0].key. this does not work

When I used var firstMonth = this.months[0] , I only see the value of 'January'. I don't see the keyvalue when accessing one of the element in the array. When I hover over the array, I see all the months with both key values.

I see the example of using *ngFor in stackblitz for angular6-keyvaluepipe-demo but I can't access the key value in the typescript file.

Any help is appreciated.

c0micrage
  • 1,118
  • 2
  • 21
  • 56
  • Possible duplicate of [How can I define an array of objects in typescript?](https://stackoverflow.com/questions/35435042/how-can-i-define-an-array-of-objects-in-typescript). Specifically, you might want to consider using an [enum](https://stackoverflow.com/a/35435117/421195) – paulsm4 Mar 01 '19 at 17:28
  • no. I am using the new angular 6.1 keyvalue pipe – c0micrage Mar 01 '19 at 17:29

1 Answers1

7

Take a look at using Object.keys(this.months).

While this may look very similar to key/value pairs, it's actually a form of indexing.

If you want to have key/value behavior out of the box, you should look at using a Map<number, string>.

Trevor
  • 481
  • 10
  • 25