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

标签 javascript jquery json html jquery-mobile

这是我的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 中获得了数据,但我想分别存储在 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"
    ]

]

您使用签名 function(index,Objvalue) 提供的匿名函数将应用于每个元素,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];
}

关于javascript - 如何使用 jquery 从 json 数组中分离值。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16734719/

相关文章:

javascript - Bootstrap 模态主体的文本内容流向外部。

javascript - Jquery Ajax 请求被调用两次并且第一个请求不在 header 中发送 token

c# - 使用 C# 的数据库结果的 JSON 数组格式

javascript - 在网络 worker 上制作自定义事件

javascript - 语义 UI 自动完成响应未按顺序到达

javascript - 字符串中的单词在中间中断,JS & CSS

jquery - Dragdealer.js 查找步骤的值

javascript - 有没有办法将多个事件添加到 $ ("body").on() 以便在更改列表或单击按钮时起作用

ruby - 使用 Her、Faraday 在 API 中进行 Rails 分页

java - 在java中解析嵌套的json数组