繁体   English   中英

如何使用jquery从json数组中分离值。

[英]How to Separate values from json array using jquery.?

这是我的json

{
  "data": [
    [
      "1",
      "Skylar Melovia"
    ],
    [
      "4",
      "Mathew Johnson"
    ]
  ]
}

this is my code jquery Code

for(i=0; i<= contacts.data.length; i++) {
    $.each(contacts.data[i], function( index, objValue ){
        alert("id "+objValue);
    });
}

我在我的objValue得到了数据,但是我想分别存储在idname数组中,看起来这看起来我的代码是下面的

var id=[];
var name = [];
for(i=0; i<= contacts.data.length; i++){
    $.each(contacts.data[i], function( index, objValue ) {
        id.push(objValue[index]); // This will be the value "1" from above JSON
        name.push(objValue[index]); // This will be the value "Skylar Melovia"   from above JSON
    });
}

我怎样才能做到这一点。

 $.each(contacts.data, function( index, objValue )
 {
    id.push(objValue[0]); // This will be the value "1" from above JSON
    name.push(objValue[1]); // This will be the value "Skylar Melovia"   from above JSON

 });

编辑,替代用法:

 $.each(contacts.data, function()
 {
    id.push(this[0]); // This will be the value "1" from above JSON
    name.push(this[1]); // This will be the value "Skylar Melovia"   from above JSON
 });

$ .each将迭代contacts.data,它是:

[
    //index 1
    [
      "1",
      "Skylar Melovia"
    ],
    //index=2
    [
      "4",
      "Mathew Johnson"
    ]

]

您使用签名函数(index,Objvalue)给出的anomnymous函数将应用于每个元素, index是contact.data数组中的索引,并且objValue其值。 对于index = 1,您将拥有:

objValue=[
          "1",
          "Skylar Melovia"
        ]

然后你可以访问objValue [0]和objValue [1]。

编辑(回应Dutchie432评论和回答;)):没有jQuery更快的方式,$ .each更好写和读,但在这里你使用普通的旧JS:

for(i=0; i<contacts.data.length; i++){
    ids.push(contacts.data[i][0];
    name.push(contacts.data[i][1];
}

也许我并不完全理解,但我认为你循环遍历数据项,然后循环遍历包含的值。 我想你想要的只是遍历数据项并分别拉取值0和1。

另外,我相信你想要循环中的less than (<)运算符而不是less than or equal to (<=)

for(i=0; i<contacts.data.length; i++){
    ids.push(contacts.data[i][0];
    name.push(contacts.data[i][1];
}

删除外部for循环。 $.each已遍历data数组。 data[i]不是数组,所以$.each不能迭代它。

http://jsfiddle.net/ExplosionPIlls/4p5yh/

您也可以使用for循环而不是$.each ,但不能同时使用两者。

暂无
暂无

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

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