如何迭代json对象结构只获取名称?

时间:2016-05-04 10:58:22

标签: javascript jquery angularjs json

我有以下json对象,如何才能获取/循环以获取名称值?

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

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

我只需要在我的提醒消息中输入名称值,例如:firstnamevalue, secondnamevalue, thirdnamevalue?请提前告知我并提前致谢。

5 个答案:

答案 0 :(得分: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 :(得分:2)

如果你使用下划线或lodash。 可以这样做:

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

数组的映射函数

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

答案 2 :(得分:1)

你可以使用for JavaScript的javascript方法

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

答案 3 :(得分:1)

我在这里简单介绍一下简单的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循环......

这是一步一步走过的漫长道路。

答案 4 :(得分:0)

完成此操作,使用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>