1
votes

I want to access object key and value in ngFor for example this is my array

var array = [
  {'random1':value1},
  {'random2':value2},
  {'random3': value3}
]

now the object keys are all dynamic and i use my array like this

<tr *ngFor="let item of arrayl; let i of index">
  <td>{{i+1}}</td>
  <td>item.key</td>// here i want object key
  <td>item.value</td>// here object value
</tr>

another question if my array look like this

var array2 = [
 ['random1',value1],
 ['random2',value2],
 ['random3',value3]
]

then how can in acheive same thing

thanks in advance

2
first array is object of array and second array is array of array. then how can you achieve same thing? what is your ultimate goal please describe - Abu Sufian
i mean in my *ngFor i want item.key = array[item][0]//first value, and for item.value = array[item][1]//second value @Abu Sufian - Akash Verma

2 Answers

4
votes

Demo case 1

<tr *ngFor="let item of array; let i = index">
   <td>{{i+1}}</td>
   <ng-container *ngFor="let el of item | keyvalue">
       <td>{{el.key}}</td>
       <td>{{el.value}}</td>
   </ng-container>
</tr>
     

case 2

<tr *ngFor="let item of array2; let i = index">
   <td>{{i+1}}</td>
   <td>{{item[0]}}</td>
   <td>{{item[1]}}</td>
</tr>
  
1
votes

It's a bit strange but you can do something like this:

First case:

<tr *ngFor="let item of array; index as i">
  <td>{{i+1}}</td>
  <td>{{ getKey(item) }}</td>
  <td>{{ item[getKey(item)] }}</td>
</tr>

// on component class
getKey(item: any): string {
  return Object.keys(item)[0];
}

Second case:

<tr *ngFor="let item of array2; index as i">
  <td>{{i+1}}</td>
  <td>{{ item[0] }}</td>
  <td>{{ item[1] }}</td>
</tr>