0

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":""}]
2
  • make your question a bit clear do you went to get the array of the name only ? Commented Dec 4, 2018 at 13:13
  • some of your values have null value so this may effect and show it as undefined Commented Dec 4, 2018 at 13:14

3 Answers 3

1

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);
})

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

Comments

0

You should use the dot operator when you are accessing property

it should be as,

res[0].name;

or

res[0]['name'];

2 Comments

that will return only the first name but i want all the names
so you have to loop or map over the items res.map(item => item.name)
0

Assuming let people = [your array of objects]

In newer JS:

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

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.