joe
joe

Reputation: 59

How to get data from api response in Angular

I'm using Angular 4, I've made a call to an api which returns an array of objects.

Then I tried to get specific data by referencing res.name but for some reason I get undefined so I tried res[0]name and res['name'] which returns only the first name but I want all the names from the array.

Here is my array:

[{"name":"joey","surname":"jackson","email":"[email protected]","phone":"0815342119"}, 
{"name":"Tim","surname":"Muller","email":"[email protected]","phone":""}, 
{"name":"Kim","surname":"Van Dam","email":"[email protected]","phone":""},
{"name":"Lyn","surname":"Davids","email":"[email protected]","phone":""}]

Upvotes: 0

Views: 1219

Answers (3)

Francesco G.
Francesco G.

Reputation: 164

Assuming let people = [your array of objects]

In newer JS:

for (person of people) { 
    console.log(person.name) 
}

Upvotes: 0

komron
komron

Reputation: 2277

Try using forEach to iterate over all elements of an array:

let res = [
{"name":"joey","surname":"jackson","email":"[email protected]","phone":"0815342119"},{"name":"Tim","surname":"Muller","email":"[email protected]","phone":""},{"name":"Kim","surname":"Van Dam","email":"[email protected]","phone":""},{"name":"Lyn","surname":"Davids","email":"[email protected]","phone":"08343435"}
];

res.forEach( (el) => {
  console.log(el.name);
})

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222722

You should use the dot operator when you are accessing property

it should be as,

res[0].name;

or

res[0]['name'];

Upvotes: 0

Related Questions