简体   繁体   English

如何遍历JSON(使用AngularJS)并将结果放入Javascript数组中?

[英]How to loop through JSON (with AngularJS) and put the results in a Javascript array?

Using the latest AngularJS version (1.3.0-rc.5), I am retrieving a simple JSON object containing people's names. 使用最新的AngularJS版本(1.3.0-rc.5),我正在检索包含人名的简单JSON对象。 Example of the JSON object: JSON对象的示例:

[{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}]

I cannot figure out how to put all the names into an associative Javascript array. 我不知道如何将所有名称放入一个关联的Javascript数组中。 In my mind I want to create an empty Javascript array and loop through the JSON object, and using .push() in the loop to keep adding the names to the array. 在我看来,我想创建一个空的Javascript数组并遍历JSON对象,并在循环中使用.push()来将名称继续添加到数组中。 But I cannot get this working in AngularJS. 但是我无法在AngularJS中使用它。

ps. ps。 I'll accept the answer that helps me out with this. 我会接受可以帮助我解决这个问题的答案。

Angular is not meant to help you with this, Angular is meant for other parts of the application (UI for instance). Angular并不能帮助您,Angular可以用于应用程序的其他部分(例如UI)。 If you want to do this, in JS it's simple: 如果要这样做,在JS中很简单:

var list = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}]
var names = []
for(var idx in list) {
  names.push(list[idx]['name'])
}

You also mentioned an associative array, in JS you have objects, which work similarly, but I don't understand how you want to use them... what is the index for that associative array? 您还提到了一个关联数组,在JS中,您有一些对象,它们的工作原理相似,但是我不明白您想如何使用它们……该关联数组的索引是什么? The name? 名字? If that's the case, then what is the value? 如果是这样,那么价值是什么? is it the ID? 是ID吗? If so, you could do something like this: 如果是这样,您可以执行以下操作:

var list = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}]
var names = {} //object literal
for(var idx in list) {
  names[list[idx]['name']] = list[idx]['id']
}

Hope that helps 希望能有所帮助

You can do this in pure javascript 您可以使用纯JavaScript做到这一点

var arr = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}];
var nameArr =[];
arr.forEach(
function(elem){ 
  nameArr.push(elem.name);
});

Use map(..) on your array object. 在数组对象上使用map(..)

var obj = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}];
var result = obj.map(function (x) {return x["name"]; });
//["John", "Jane", "Pete"]

使用angular.fromJson()函数解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM