我有这些数组
countryList = ["United Kingdom", "France", "Tajikstan"]
countryDetails = ["Markets", "Government", "Details"]
countryFactors = ["Capital", "Labour", "Land"]
marketList = ["Primary", "Secondary", "Service"]
businessList = ["Businesses", "Info"]
supplyAndDemand = ["Supply", "Demand", "Price"]
我希望这些数组形成如下对象
Country.list ={
"United Kingdom":{
"Markets":{
"Primary":{
"Businesses":{},
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Secondary":{
"Businesses":{},
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Service":{
"Businesses":{},
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
},
"Government":{
},
"Details":{
"Capital":{
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Labour":{
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Land":{
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
},
},
"France":{
"Markets":{
"Primary":{
"Businesses":{},
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Secondary":{
"Businesses":{},
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Service":{
"Businesses":{},
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
},
"Government":{
},
"Details":{
"Capital":{
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Labour":{
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
"Land":{
"Info":{
"Suppy":0,
"Demand":0,
"Price":0,
},
},
},
},
}
所以基本上取决于数组的名称,决定了之后会发生什么。因此,如果数组名称为“Markets”,那么该数组下面将是“marketList”数组。等
有没有人有想法?我想在循环之后做一个if语句,但if语句一直在修改我的代码。
以下是我一直在做的代码示例:https://jsfiddle.net/4vcru3a0/
答案 0 :(得分:2)
您可以对任何深度的嵌套对象使用动态方法。
function iter(object, i) {
data[i].forEach(function (k) {
if (i + 1 < data.length) {
object[k] = {};
iter(object[k], i + 1);
} else {
object[k] = 0;
}
});
}
var data = [["United Kingdom", "France", "Tajikstan"], ["Markets", "Government", "Details"], ["Capital", "Labour", "Land"], ["Primary", "Secondary", "Service"], ["Businesses", "Info"], ["Supply", "Demand", "Price"]],
tree = {};
iter(tree, 0);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }