2016-05-04 48 views
-3

我有以下json對象,我怎樣才能得到/名稱值的循環?如何迭代json對象結構以獲取唯一名稱?

var jsonobject = { 
    "jsontest": [{ 
     "name": "firstnamevalue", 
     "firstkey": "firstvalue" 

    }, { 
     "name": "secondnamevalue", 
     "secondkey": "secondvalue", 
     "thirdkey": false 
    }, { 
     "name": "thirdnamevalue", 
     "fourthkey": null 
    }], 
    "fifthkey": "testvalues" 
} 

我只需要名稱值,如:firstnamevalue, secondnamevalue, thirdnamevalue在我的警報消息?請讓我知道並提前致謝。

+1

你可以很容易地使用一個簡單的for循環,因爲'jsonobject.jsontest'是一個數組 – Satpal

+1

或者'Array#map' .. – Rayon

回答

2

您可以使用javascript map方法根據您的要求獲取數組值。

var results = jsonobject.jsontest.map(function(item,index){ 
    return item["name"]; 

    }) 
    results // 
["firstnamevalue", "secondnamevalue", "thirdnamevalue"] 

ES2015脂肪箭頭(ES6)

jsonobject.jsontest.map((item,index)=> item["name"]) 
1

如果使用下劃線或lodash您可以使用JavaScript

var arr=jsonobject.jsontest; 
arr.forEach(function(item, index){console.log(item.name)}) 
2

的方法的forEach。 ,它可以像做:數組

var names= jsonobject.jsontest.map(function(item,index){ 
    return item["name"]; 
    }) 
+0

pluck在lo dash中不推薦使用,但是你可以用相同的方式使用map,所以我會顯示'_.map'代替你的'_.pluck' – Zargold

0

經歷這個的

_.pluck(jsonObject.jsonTest, 'name'); 

地圖功能,使用jsonobject.jsontest解決您的問題

var jimApp = angular.module("mainApp", []); 
 

 
jimApp.controller('mainCtrl', function($scope){ 
 
    var jsonobject = { 
 
    "jsontest": [{ 
 
     "name": "firstnamevalue", 
 
     "firstkey": "firstvalue" 
 

 
    }, { 
 
     "name": "secondnamevalue", 
 
     "secondkey": "secondvalue", 
 
     "thirdkey": false 
 
    }, { 
 
     "name": "thirdnamevalue", 
 
     "fourthkey": null 
 
    }], 
 
    "fifthkey": "testvalues" 
 
}; 
 
    
 
    $scope.results = jsonobject.jsontest.map(function(item,index){ 
 
    return item["name"]; 
 

 
    }) 
 
}); 
 

 

 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="mainApp" ng-controller="mainCtrl"> 
 
    {{results}} 
 
</div>

+0

角碼完全多餘,只會污染答案 –

+0

同樣,如果你要顯示的HTML可能只是使用' ''{{person.name}}' Zargold

1

我我只需要投入她E中的簡單JavaScript解決方案:首先 你可能要分析出這個JSON,因爲你有角,你可以放心地使用`angular.fromJson(OBJ)」

var jsonObj = angular.fromJson(jsonobject)

然後

var nameArray = [];

解析

設置您可以存儲名稱的空數組,或者您可以使用map,但不是那麼簡單。

for (var i = 0; i < jsonObj.jsonsontest.length; i++){

設置爲循環..

nameArray.push(jsonObj.jsonsontest[i].name);

添加元素

} 關閉一個for循環...

那通過一步一個長期行走步。