如何使用jQuery $ .each访问特定键:对象数组中每个对象的值?

时间:2013-12-04 09:33:41

标签: jquery arrays each

架构(MongoDB):

key0: [
  {
     skey1: "sval1",
     skey2: "sval2"
  },
  {
     skey1: "sval3",
     skey2: "sval4"
  },
]

getJSON()回复:

[Object { skey1="val1", skey2="val2"}, Object { skey1="val3", skey2="val4"}]

问题:

如何为每个对象访问skey2的值?

jQuery(尝试):

my_var = results.key0

$.each(my_var, function(k,v) {
alert(v);
});

我想我需要做一些'嵌套'$.each但不确定语法。

2 个答案:

答案 0 :(得分:1)

这似乎有效:

的jsfiddle:

http://jsfiddle.net/rwone/Yg5cg/4/

// aim:  to alert value of 'skey2' for each object

myArray = [{ skey1:"val1", skey2:"val2"}, { skey1:"val3", skey2:"val4"}]

$.each(myArray, function(k,v) {
  alert(v.skey2);
});

答案 1 :(得分:0)

尝试:

var my_var = [{
    skey1: "sval1",
    skey2: "sval2"
}, {
    skey1: "sval3",
    skey2: "sval4"
}, ];
var len = my_var.length;
for (var i = 0; i < len; i++) {
    $.each(my_var[i], function (k, v) {
        alert("key"+k+"value"+v);
    });
}

DEMO here.