angular如何在json数组中显示键

时间:2015-07-03 12:28:20

标签: javascript arrays json angularjs

我有以下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);
       };

但它不起作用!!

5 个答案:

答案 0 :(得分:2)

你在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

答案 1 :(得分:2)

遍历Javascript数组时,请使用标准for循环而不是for...in

for (var i=0; i < employees.length; i+=1) {
    console.log(employees[i].lastname);
}

或者,ES5现在提供了一个Array.forEach功能,也可以使用。

employees.forEach( function (employee) { 
  console.log(employee.lastname);
}

答案 2 :(得分:1)

试试这个

for (var index in employees) {
    var tp = employees[index];
    console.log(tp['yourkeyhere']);
}

答案 3 :(得分:1)

方法:1 - 更多验证。

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

for(var obj in employees) {
    if(employees.hasOwnProperty(obj)){
        for(var prop in employees[obj]){
            if(employees[obj].hasOwnProperty(prop)){
                alert(prop + ' : ' + employees[obj][prop]);
                //to change the key's value
                if(employees[obj][prop] == 'Smith'){
                    employees[obj][prop]='Mike';
                } 
            }
        }
    }
}

Plunker

方法:2 未经验证(不推荐)

   for(i in employees) {
       var obj = employees[i];
       for(j in obj) {
           var key = j;
           var val = obj[j];
           alert(key + " : " + val);   
       }
    }

修改

var employees={"firstName":"John", "lastName":"Doe"};
Object.keys(employees); // return ["firstName", "lastName"]

Object有一个prototype keys,在Array

中返回keys ObjectObject.keys

Chrome,FF&amp; Safari支持 <RatingBar android:id="@+id/listitemrating" style="@android:attr/ratingBarStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleX=".5" android:scaleY=".5" android:transformPivotX="0dp" android:transformPivotY="0dp" android:isIndicator="true" android:max="5" />

答案 4 :(得分:1)

将您的代码更改为以下内容。 它工作正常。

employees=[
        {"firstName":"John", "lastName":"Doe"}, 
        {"firstName":"Anna", "lastName":"Smith"}, 
        {"firstName":"Peter","lastName":"Jones"}
    ]
    for(var ke in employees) {
           if (employees.hasOwnProperty(ke)) {
                 console.log(employees[ke].lastName);
           };
   }