Bolin
Bolin

Reputation: 138

How to use the key of an keyvalue object as propperty name of an other object in angular template

How to use the key of an keyvalue object as propperty name of an other object in angular template

<ion-col *ngFor="let item of items | keyvalue">
{{ (stati | async)?.[item.key] }} // doesn't work
</ion-col>

item.key is the name of the property I need from "stati"?

Object Examples:

items: { 
  item1: {id: 1, title: "xy", ... }, 
  item1: {id: 2, title: "xy", ... }, 
  item1: {id: 2, title: "xy", ... }
}
stati: { 
  'item1': 'xy1', 
  'item2': 'xy2', 
  'item3': 'xy3' 
}

What I need: Only the value of the stati object with the corresponding key.

Upvotes: 1

Views: 309

Answers (2)

code
code

Reputation: 44

Try using object.keys and the index of the key you need

let objArr = [
    'apple',
    'microsoft',
    'amazon',
    'alphabet',
    'tencent',
    'alibaba'
];
console.log(Object.keys(objArr))

From the key you can fetch the respective value from the object

var requiredKey = Object.keys(objArr)[2] //amazon
var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: requiredKey});
//There are other ways too

Hope this answers your question.

Upvotes: 0

Tiep Phan
Tiep Phan

Reputation: 12596

(stati | async) could return undefined, or null. Try to wrap with if condition:

<ng-container *ngIf="(stati | async) as _stati">
  <ion-col *ngFor="let item of items | keyvalue">
    {{ _stati[item.key] }}
  </ion-col>
</ng-container>

Upvotes: 2

Related Questions