2

The array consists of a key and value pair of objects.i want iterate through to fetch key and values of object.

var arr = [{fruit: banana},{color: red},{city: London},{count: 10},{price: 100$}];

i tried using keyvalue pipe

<div class="bx--row" *ngFor="let obj of arr | keyvalue; let i = index;">
     <span class="bx--col-xs-5 bx--col-md-5"> {{obj.key}} :</span>
     <span class="bx--col-xs-5 bx--col-md-5">{{obj.value}} </span>
</div>

Expected result:

fruit : banana
color: red
city: London
count : 10
price : 100$
1

2 Answers 2

3

You might need two *ngFor directives. Try the following

<div class="bx--row" *ngFor="let obj of arr; let i = index;">
  <ng-container *ngFor="let item of obj | keyvalue">
    <span class="bx--col-xs-5 bx--col-md-5"> {{item.key}} :</span>
    <span class="bx--col-xs-5 bx--col-md-5">{{item.value}} </span>
  <ng-container>
</div>

Or you could merge the individual objects to a single object in the controller and iterate it with a single *ngFor.

Controller

const arr = [{fruit: 'banana'},{color: 'red'},{city: 'London'},{count: 10},{price: '100$'}];
const obj = Object.assign({}, ...arr)

Template

<div class="bx--row" *ngFor="let item of obj | keyvalue; let i = index;">
  <span class="bx--col-xs-5 bx--col-md-5"> {{item.key}} :</span>
  <span class="bx--col-xs-5 bx--col-md-5">{{item.value}} </span>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this

in html

<div class="bx--row" *ngFor="let obj of arr">
     <span class="bx--col-xs-5 bx--col-md-5"> {{objectKeys(obj)}} :</span>
     <span class="bx--col-xs-5 bx--col-md-5">{{obj[objectKeys(obj)]}} </span>
</div>

in ts

objectKeys(obj){
 return Object.keys(obj)[0];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.