javascript – 如何使用jquery从json数组中分离值.?

前端之家收集整理的这篇文章主要介绍了javascript – 如何使用jquery从json数组中分离值.?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是我的json

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

这是我的代码jquery代码

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

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

var id=[];
var name = [];
for(i=0; i<= contacts.data.length; i++){
    $.each(contacts.data[i],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,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",//index=2
    [
      "4","Mathew Johnson"
    ]

]

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

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

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

编辑(回应Dutchie432评论和回答;)):
没有jQuery就可以更快地完成它,$.each可以更好地编写和读取,但在这里你使用普通的旧JS:

for(i=0; i
原文链接:https://www.f2er.com/jquery/428202.html

猜你在找的jQuery相关文章