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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:47:17  来源:igfitidea点击:

How to get value array of object using jquery

jqueryarraysmultidimensional-array

提问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 有点矫枉过正。

Array.forEach:

Array.forEach

test.Persons.forEach(function(person) {
  alert(person.FirstName + " " + person.LastName);
});

or simply by index:

或者简单地通过索引:

alert(test.Persons[0].FirstName + " " + test.Persons[0].LastName);