gpt4 book ai didi

javascript - 迭代json数组并将每个值推送到angular js中的列表

转载 作者:可可西里 更新时间:2023-11-01 00:42:16 26 4
gpt4 key购买 nike

我对 Angular JS 很陌生。我的问题是,我有一个 json 数组,我从 php 页面获取它作为 ajax 响应。我正在迭代那个 json 数组,我想像这样推送列表中的每个值

angular.forEach($scope.companies.area, function(value, key) {
$scope.comp = [
{ 'name': value1 },
{ 'name': value2 },
{ 'name': value3 }
//...
]
});

我怎样才能列出这个 list ?我的Json数据是

{"1":"Audugodi","2":"Yelahanka 空军基地","3":"Agaram","4":"Anadanagar","5":"阿拉伯学院","6":"Banasawadi","7":"Banashankari","8":"Banashankari II 阶段","9":"Banashankari III 阶段","10":"类加罗尔 city","11":"Bangalore GPO","12":"Bannerghatta","13":"Bannerghatta Road","14":"Basavanagudi","15":"Basaveswaranagar"

最佳答案

使用简单的 Array.prototype.map 会更容易:

  $scope.comp = $scope.companies.area.map(function(value) {
return { name: value };
});

由于您的数据实际上是对象格式,因此必须稍作更改才能将其与 .map 一起使用(原始 JSON 数据在底部以供引用):

helloApp.controller("CompanyCtrl", function ($scope, $http) {
$http.post('class_locaality.php?flag=1').success(function (data) {
$scope.companies = data; // the original data - we need data.area
$scope.comp = Object.keys(data.area).map(function (key) { // turn the object into a array of keys that we can iterate
return {
name : data.area[key] // get the value from the original data.area using the key
};
});
}).error(function (data) { // log error }); });


{
"1" : "Audugodi",
"2" : "Airforce Station Yelahanka",
"3" : "Agaram",
"4" : "Anadanagar",
"5" : "Arabic College",
"6" : "Banasawadi",
"7" : "Banashankari",
"8" : "Banashankari II Stage",
"9" : "Banashankari III Stage",
"10" : "Bangalore city",
"80" : "St.Thomas Town",
"81" : "Subramanyanagar",
"95" : "Yelahanka",
"96" : "Yeshwanthpur"
}

关于javascript - 迭代json数组并将每个值推送到angular js中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32037881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com