JSON数据警报未定义

时间:2016-02-22 10:16:10

标签: jquery json

我通过AJAX检索这个JSON:

[{
    "tid": "1",
    "itemID": "Camry",
    "item_type": "Carf",
    "vendor_id": "ogbueli"
}, {
    "tid": "2",
    "itemID": "Samsung",
    "item_type": "Electronics",
    "vendor_id": "Chizoba"
}, {
    "tid": "3",
    "itemID": "Panasonic",
    "item_type": "Electronics",
    "vendor_id": "Mourinho"
}]

我已经解析了它:

arr = JSON.parse(response);

现在我想像这样访问它:

for (var i in arr){
    newitems = arr[0];
    alert(newitems);
}

警报正在返回undefined。我想得到这样的东西:

newitems = { '1', 'camry', 'carf', 'ogbueli' };

希望有人可以帮助我。感谢。

2 个答案:

答案 0 :(得分:0)

这是解决方案。

var arr = [{"tid":"1","itemID":"Camry","item_type":"Carf","vendor_id":"ogbueli"},{"tid":"2","itemID":"Samsung","item_type":"Electronics","vendor_id":"Chizoba"},{"tid":"3","itemID":"Panasonic","item_type":"Electronics","vendor_id":"Mourinho"}];


var newitems = [], item;

for(var i in arr){
	
  // get item
  item = [arr[i].tid, arr[i].itemID, arr[i].item_type, arr[i].vendor_id];
  
  // push it to newitems array
  newitems.push(item);
  
}

alert(newitems[0]);
alert(newitems[1]);
alert(newitems[2]);

答案 1 :(得分:0)

你可以使用它。



a = [{"tid":"1","itemID":"Camry","item_type":"Carf","vendor_id":"ogbueli"},{"tid":"2","itemID":"Samsung","item_type":"Electronics","vendor_id":"Chizoba"},{"tid":"3","itemID":"Panasonic","item_type":"Electronics","vendor_id":"Mourinho"}];

for(i=0; i < a.length; i++){
  var val = a[i];
  newitems = [val.tid, val.itemID, val.item_type, val.vendor_id];
  alert(JSON.stringify(newitems));
}
&#13;
&#13;
&#13;