var all_area = [];
$.each(data,function(i,v){
$.each(v.areas,function(a,b){
all_area[i]['id'] = b.id;
all_area[i]['name'] = b.name;
});
});
我想要一个包含这些数据的数组:
all_area[0]['id'] = 1;
all_area[0]['name'] = "test";
all_area[1]['id'] = 2;
all_area[1]['name'] = "test123";
我的代码无效。我收到此错误:
Uncaught TypeError: Cannot set property 'id' of undefined
这是我从ajax调用中获取的示例数据:
[
{
"name": "Dubai",
"id": "1",
"areas": [
{
"name": "Deira",
"id": 1,
"extra_fee": 0,
"extra_time": 0,
"min_order": 0
},
{
"name": "Bur Dubai",
"id": 2,
"extra_fee": 5,
"extra_time": 10,
"min_order": 100
}
]
},
{
"name": "Abu Dhabi",
"id": "2",
"areas": [
{
"name": "Shahama",
"id": 3,
"extra_fee": 0,
"extra_time": 0,
"min_order": 0
},
{
"name": "City Center",
"id": 4,
"extra_fee": 5,
"extra_time": 10,
"min_order": 100
}
]
}
]
感谢。
答案 0 :(得分:3)
初始化对象
$.each(v.areas,function(a,b){
all_area[i] = {};
all_area[i]['id'] = b.id;
all_area[i]['name'] = b.name;
});
OR ,
$.each(v.areas,function(a,b){
all_area[i] = {
id : b.id,
name : b.name
};
});