How to access items from array

3935 views javascript
0

I want to display the name and photoUrl in the HTML template of an Angular 6 app, how do I access the name and photoUrl elements only in the below array:

{
   "key":"key0",
   "value":[
      {
     "id":567657,
     "name":"Jess",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/female-50.jpeg",
     "rating":30
  },
  {
     "id":3243242,
     "name":"Ryan",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/male-29.jpg",
     "rating":5
  }
   ]
}

{  
   "key":"key1",
   "value":[  
  {  
     "id":567657,
     "name":"Jess",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/female-50.jpeg",
     "rating":30
  },
  {  
     "id":6757587,
     "name":"Sarah",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/female-70.jpg",
     "rating":16
  }
   ]
}

answered question

your JSON have syntax error!

2 Answers

13

You can use *ngFor directive provided by Angular

.component.html

<div *ngFor="let user of users">
 <div *ngFor="let value of values;i = index">
  <div>{{value.name}}</div>
  <div>{{value.photoUrl}}</div>
 </div>
<div>

.component.ts

users = [
 {
   "key":"key0",
   "value":[
      {
     "id":567657,
     "name":"Jess",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/female-50.jpeg",
     "rating":30
  },
  {
     "id":3243242,
     "name":"Ryan",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/male-29.jpg",
     "rating":5
  }
   ]
}.
{  
   "key":"key1",
   "value":[  
  {  
     "id":567657,
     "name":"Jess",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/female-50.jpeg",
     "rating":30
  },
  {  
     "id":6757587,
     "name":"Sarah",
     "photoUrl":"https://d3iw72m71ie81c.cloudfront.net/female-70.jpg",
     "rating":16
  }
   ]
 }
]

posted this
1

Your JSON is not valid, however i made few adjustments

[ { "key": "key0", "value": [ { "id": 567657, "name": "Jess", "photoUrl": "https://d3iw72m71ie81c.cloudfront.net/female-50.jpeg", "rating": 30 }, { "id": 3243242, "name": "Ryan", "photoUrl": "https://d3iw72m71ie81c.cloudfront.net/male-29.jpg", "rating": 5 } ] }, { "key": "key1", "value": [ { "id": 567657, "name": "Jess", "photoUrl": "https://d3iw72m71ie81c.cloudfront.net/female-50.jpeg", "rating": 30 }, { "id": 6757587, "name": "Sarah", "photoUrl": "https://d3iw72m71ie81c.cloudfront.net/female-70.jpg", "rating": 16 } ] } ]

and you just need nested ngFor as follows,

<ul>
    <li *ngFor="let group of myArray">
    {{group.name}}
    <ul>
        <li *ngFor="let light of group.value">
            <h1>Photo </h1>  {{light.photoUrl}}
            <h1>Name </h1>    {{light.name}}
        </li>
    </ul>
    </li>
</ul>

STACKBLITZ DEMO

posted this

Have an answer?

JD

Please login first before posting an answer.