jQuery 如何使用jquery获取对象的值数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4710965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value array of object using jquery
提问by Sthepen
i have problem to get all element in array of object using jquery...
我在使用 jquery 获取对象数组中的所有元素时遇到问题...
i get this code from internet...
我从网上得到这个代码...
var id = 123;
var test = new Object();
test.Identification = id;
test.Group = "users";
test.Persons = new Array();
test.Persons.push({"FirstName":" AA ","LastName":"LA"});
test.Persons.push({"FirstName":" BB ","LastName":"LBB"});
test.Persons.push({"FirstName":" CC","LastName":"LC"});
test.Persons.push({"FirstName":" DD","LastName":"LD"});
how to get each of "FirstName" and "LastName" in Persons using JQuery??
如何使用 JQuery 获取 Persons 中的“FirstName”和“LastName”?
回答by polarblau
You could use $.each()
or $.map()
, depending on what you want to do with it.
您可以使用$.each()
或$.map()
,具体取决于您想用它做什么。
$.map(Persons, function(person) {
return person.LastName + ", " + person.FirstName;
});
// -> ["Doe, John", "Appleseed, Marc", …]
回答by rahul
You can use $.each()
to iterate through the array.
您可以使用$.each()
遍历数组。
$.each(test.Persons, function(index){
alert(this.FirstName);
alert(this.LastName);
});
See a working demo
查看工作演示
回答by Liutas
You can use JavaScript syntax for array:
您可以对数组使用 JavaScript 语法:
for(var i in test.Persons) {
alert(test.Persons[i].FirstName + " " + test.Persons[i].LastName);
}
回答by Jakob
Using jQuery for that is a little overkill imho.
恕我直言,使用 jQuery 有点矫枉过正。
test.Persons.forEach(function(person) {
alert(person.FirstName + " " + person.LastName);
});
or simply by index:
或者简单地通过索引:
alert(test.Persons[0].FirstName + " " + test.Persons[0].LastName);