这是我的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], 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/