RuD3B0y
RuD3B0y

Reputation: 141

How to display {object object} in a table?

Actually I want to display this data into a table. Here, the data was {object object}. I want to display all values of "last", "buy" & "sell" from all currencies. I can do hard code, but I want to reduce the lines of code by using ng-repeat or ngFor. How to write the conditions for this?

I'm using Angular 4.

Upvotes: 1

Views: 2623

Answers (3)

RuD3B0y
RuD3B0y

Reputation: 141

Thanks for the replies guys, your ways were working fine. But i found more easier way to do this:

function generateArray(obj) {
  return Object.keys(obj).map((key) =>  obj[key] );
}

this will convert the json object to array and

<tr *ngFor="let post of posts">
            <td>{{post.last}}</td>
            <td>{{post.buy}}</td>
            <td>{{post.sell}}</td>  
          </tr>

this will iterate the json into a table.

P.S: I've saved the json into "posts" called "obj" from "posts".

Upvotes: 1

JeanPaul A.
JeanPaul A.

Reputation: 3724

ngFor works on iterables, thus in your case you need to first transform the json data into an array.

let blockChainData:any = { ... } //data.retrieved.from.server;
let blockChainDataArray:Array<any> = [];

let dataKeys:Array<string> = Object.keys(blockChainData);
dataKeys.forEach((key:string) => {
   let entry:any = blockChainData[key]; // Retrieve the object associated with the currency
   entry.originalCurrency = key; // Preserve the original currency
   blockChainDataArray.push(entry);
});

In your html code, iterate over the array

<td *ngFor="let entry of blockChainDataArray">{{ entry.originalCurrency }} {{ entry.buy }} {{ entry.sell }} {{ entry.last }} </td>

Upvotes: 0

Hardik Patel
Hardik Patel

Reputation: 3949

You need to create a pipe and then you can iterate through object.

@Pipe({ name: 'ObjNgFor',  pure: false })
export class ObjNgFor implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)//.map(key => value[key]);
    }
}

This plnkr might help you.

plnkr

Upvotes: 2

Related Questions