gpt4 book ai didi

javascript - 从数组创建动态对象树

转载 作者:行者123 更新时间:2023-11-30 15:26:25 25 4
gpt4 key购买 nike

我有这些数组

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/

最佳答案

您可以对任何深度的嵌套对象使用动态方法。

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; }

关于javascript - 从数组创建动态对象树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com