如何从Angular的api响应中获取数据

时间:2018-12-04 13:06:23

标签: javascript arrays angular

我正在使用Angular 4,我已经调用了一个返回对象数组的api。

然后,我尝试通过引用res.name来获取特定数据,但是由于某种原因,我无法定义,所以我尝试了res[0]nameres['name'],它们仅返回名字,但我想要所有名字从数组。

这是我的数组:

[{"name":"joey","surname":"jackson","email":"joey@gmail.com","phone":"0815342119"}, 
{"name":"Tim","surname":"Muller","email":"tim@gmail.com","phone":""}, 
{"name":"Kim","surname":"Van Dam","email":"kim@gmail.com","phone":""},
{"name":"Lyn","surname":"Davids","email":"lyn@gmail.com","phone":""}]

3 个答案:

答案 0 :(得分:1)

尝试使用forEach遍历数组的所有元素:

let res = [
{"name":"joey","surname":"jackson","email":"joey@gmail.com","phone":"0815342119"},{"name":"Tim","surname":"Muller","email":"tim@gmail.com","phone":""},{"name":"Kim","surname":"Van Dam","email":"kim@gmail.com","phone":""},{"name":"Lyn","surname":"Davids","email":"lyn@gmail.com","phone":"08343435"}
];

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

答案 1 :(得分:0)

访问属性时,应使用点运算符

应为

res[0].name;

res[0]['name'];

答案 2 :(得分:0)

假设let people = [your array of objects]

在较新的JS中:

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