我有以下对象的JSON数组:

"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName":"Jones"}
]


我想在JSON数组中获取特定的键:

for (var ke in employees) {
       if (employees.hasOwnProperty(ke)) {
             console.log(employees[ke].lastName);
       };


但它不起作用!

最佳答案

您在for循环的末尾缺少左花括号,它应该是:

for (var ke in employees) {
   if (employees.hasOwnProperty(ke)) {
         console.log(employees[ke].lastName);
   };
}


Demo

但是,您可以改用angular.forEach,如下所示:

angular.forEach(employees, function (ke) {
    if(ke.lastName) {
        console.log(ke.lastName);
    }
});


Demo

关于javascript - Angular 如何在json数组中显示键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31206890/

10-13 03:38