如何在jQuery中迭代数组中的对象?

时间:2015-11-25 14:17:01

标签: jquery

我有一个JSON对象:

[{
     name:'bhavani',
     age:'19',
     gender:'Female'
},{
     name:'bhavani',
     age:'19',
     gender:'Female'
},{
     name:'bhavani',
     age:'19',
     gender:'Female'
}, {
     // and so on
}]

现在我需要在JSP页面中访问此数组中每个对象的name。我无法做到。任何人都可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

要遍历数组或对象的属性,可以使用$.each函数。

小提琴:http://jsfiddle.net/AtheistP3ace/ohswrnmn/

var data = [{
    name: 'bhavani',
    age: '19',
    gender: 'Female'
}, {
    name: 'bhavani',
    age: '19',
    gender: 'Female'
}, {
    name: 'bhavani',
    age: '19',
    gender: 'Female'
}, ];

var $test = $('#test');
$.each(data,
    function (index, value) {
        $test.append(value.name + ' ');
    }
);

jQuery docs:http://api.jquery.com/jquery.each/

循环遍历数组和每个对象属性的示例:

小提琴:http://jsfiddle.net/AtheistP3ace/ohswrnmn/1/

var data = [{
    name: 'bhavani',
    age: '19',
    gender: 'Female'
}, {
    name: 'bhavani',
    age: '19',
    gender: 'Female'
}, {
    name: 'bhavani',
    age: '19',
    gender: 'Female'
}, ];

var $test = $('#test');
$.each(data,
    function (index, value) {
        $test.append(index + ': ');
        $.each(value,
            function (index2, value2) {
                $test.append(value2 + ' ');
            }
        );
        $test.append(' - ');
    }
);

答案 1 :(得分:0)

jQuery在这里没有任何意义,只需映射你的数组:

var names = arr.map(function(o){
   return o.name; 
});

-jsFiddle-