3

Let's say we have a list of JSON object like this one:

data = {
   id: 1,
   someObjAsString: '{"p1":"a", "p2": "b"}',
   ...
   ... other properties
}

Using *ngFor I want to display p2 from someObjAsString:

<div *ngFor="let data of dataList">
{{data.someObjAsString.p2}} <!-- What should I do here to display p2 property of someObjAsString-->
</div

JSON.parse() is definitly not working

Any help would be appreciated.

1 Answer 1

3

As someObjAsString is object, then you can use keyvalue pipe:

<div *ngFor="let item of dataList.someObjAsString | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

Usually ngFor is used to iterate through arrays.

UPDATE:

As your object is stored as string, then we can use json.parse() to construct the JavaScript value or object:

data = {
  id: 1,
  someObjAsString: '{"p1":"a", "p2": "b"}',
  anotherObj: '{"p1":"a", "p2": "b"}'
};


ngOnInit(){
    for (const key in this.data) {
        if (this.data.hasOwnProperty(key)) {
             this.data[key] = JSON.parse(this.data[key]);
        }
     }
     console.log(this.data);
}

And HTML:

<div *ngFor="let item of data | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value | json}}</b>

    <div *ngFor="let someObj of item | keyvalue">
        someObj Key: <b>{{someObj.key}}</b> 
          and someObjValue: <b>{{someObj.value | json}}</b>
    </div>
</div>

A complete workstackblitz example can be see here.

Sign up to request clarification or add additional context in comments.

1 Comment

but I need other properties of the item also, Which doesn't seem to be accessible inside loop using your solution

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.