这让我发疯了。
假设我有这个:
var tags = ["art","wedding"];
var containers = ["artcon","weddingcon"];
var limits = [5,15];
如何像这种结构一样创建这种类型的多级数组?
var testarr = [
"art" = [
"container" = "artcon",
"limit" = 5,
],
"wedding" = [
"container" = "weddingcon",
"limit" = 15,
]
];
最好的问候。
答案 0 :(得分:4)
您可以使用Array#reduce
并返回对象
var tags = ["art", "wedding"];
var containers = ["artcon", "weddingcon"];
var limits = [5, 15];
var result = tags.reduce((res, e, i) => {
res[e] = {container: containers[i], limit: limits[i]}
return res;
}, {})
console.log(result)

答案 1 :(得分:1)
只需要一个for
循环
var tags = ["art","wedding"];
var containers = ["artcon","weddingcon"];
var limits = [5,15];
//
var obj =[];
for(i in tags){
obj[tags[i]]=[containers[i],limits[i]];
}
console.log(obj);
//
响应:
[art: Array[2], wedding: Array[2]]
art:Array[2]
0:"artcon"
1:5
length:2
wedding:Array[2]
0:"weddingcon"
1:15
length:2
答案 2 :(得分:0)
var testarr = {
"art": {
"container": "artcon",
"limit": 5,
},
"wedding": {
"container": "weddingcon",
"limit": 15,
}
};
这是对你的想法的一个非常简单的修改。请注意在对象声明中,我们始终使用:
而不是=
。此外,对象声明使用花括号而不是方括号。
我们可以用这个对象做什么?我们可以循环遍历它,尽管不像那样和数组一样可靠。
例如,我们可以执行for (key in testarr)
,循环将执行两次,一个key
为"art"
,另一个为"wedding"
。这有一些警告...但在这样一个简单的用例中你可能会没事。
虽然,如果您的问题是如何将这三个对象通过代码转换为该对象结构,请告诉我,因为现在您似乎只是想了解如何对象或"多级数组"在这种情况下工作。
答案 3 :(得分:0)
var tags = ["art","wedding"];
var containers = ["artcon","weddingcon"];
var limits = [5,15];
testarr = new Array();
for(i in tags){
var obj = {};
obj[tags[i]] = { container: containers[i], limit: limits[i] };
testarr.push(obj)
}
console.log(testarr);
console.log(testarr[0]);
console.log(testarr[1]);
数组结果:
[
{ "art": {
"container": "artcon",
"limit": 5,
}
},
{ "wedding": {
"container": "weddingcon",
"limit": 15,
}
}
];
var tags = ["art","wedding"];
var containers = ["artcon","weddingcon"];
var limits = [5,15];
testarr = new Array();
for(i in tags){
testarr.push({tag: tags[i], container: containers[i], limit: limits[i] })
}
console.log(testarr);
console.log(testarr[0]);
console.log(testarr[1]);
数组结果:
[
{ "tag": "art",
"container": "artcon",
"limit": 5
},
{ "tag": "wedding",
"container": "weddingcon",
"limit": 15
}
];