我想要实现的目标:
为每个国家/地区'item_location'创建一个数组,并以'item_location'作为键来推送对象值。
e.g
[{USA:1},{USA:2}], [{UK:1},{UK:2}], [{CUBA:1},{CUBA:2}]
或
e.g
[
{
USA: {"Activity/Adventure": 1, "Beach Escape": 2},
UK: {"Activity/Adventure": 1, "Beach Escape": 2},
CUBA: {"Activity/Adventure": 1, "Beach Escape": 2}
}
]
当前问题:
对象键表示'item_location'而不是拾取'item_location'var值'item.Location'。
var filter = [];
for(var ix = 0; ix < jsonData.length; ix++)
{
var item = jsonData[ix];
var item_location = item.Location;
var item_ = [{item_location:item["Activity/Adventure"]},{item_location:item["Beach Escape"]}];
filter.push({item_});
}
console.log(filter);
ANWSER:
function filterData(){
var filter = [];
for(var ix = 0; ix < jsonData.length; ix++)
{
var item = jsonData[ix];
var item_location = item.Location;
var item1 = {}, item2= {};
item1[item_location] = item["Activity/ Adventure"];
item2[item_location] = item["Beach Escape"];
var item_ = [item1, item2];
filter.push(item_);
}
console.log(filter);
}
答案 0 :(得分:0)
密钥是item_location
,因为这是您设置的内容。您不能将变量用作对象文字中的键名。
您需要创建一个新对象,然后使用obj[key]
语法添加密钥。
var item_location = item.Location;
var item1 = {}, item2= {};
item1[item_location] = item["Activity/Adventure"];
item2[item_location] = item["Beach Escape"];
var item_ = [item1, item2];
filter.push(item_);