gpt4 book ai didi

javascript - 如何遍历对象并创建树对象

转载 作者:搜寻专家 更新时间:2023-11-01 04:17:54 25 4
gpt4 key购买 nike

我有一个平面对象和一个数组,我需要从中构造一个树状对象。

choices: ['choice1', 'choice2', 'choice3'];
items: [
{
choice1: 'taste',
choice2: 'good',
choice3: 'green-lemon'
},
{
choice1: 'taste',
choice2: 'bad',
choice3: 'green-lemon'
}
];

数组描述了每个选择在树中的级别。不知道以后会有多少选择,项目,关卡。

如何获取以下对象:

output: {
taste: {
good: {
green-lemon:1
},
bad: {
green-lemon:1
}
}
}

我需要一个对象来描述每个级别上有多少项目。在此示例中,这是 choice1: 1; choice2: 2 和每个 choice3: 1

关于如何构建循环以获得此结果有什么建议吗?

最佳答案

我认为这里最好的解决方案是使用一些递归的循环。我在示例中增加了模型的大小,以显示它有 n 个级别。使用您的 JavaScript 控制台检查输出。

var choices = ['choice1', 'choice2', 'choice3'];
var items = [{
choice1: 'taste',
choice2: 'good',
choice3: 'green-lemon'
}, {
choice1: 'taste',
choice2: 'bad',
choice3: 'green-lemon'
},
{
choice1: 'taste',
choice2: 'ok',
choice3: 'green-lemon'
},
{
choice1: 'taste',
choice2: 'ok',
choice3: 'green-lemon'
}];

function IsLastLevel(levelIndex) {
return (levelIndex == choices.length - 1);
}

function HandleLevel(currentItem, currentLevel, nextChoiceIndex) {

var nextLevelName = currentItem[choices[nextChoiceIndex]];

if (typeof currentLevel[nextLevelName] === 'undefined') {
currentLevel[nextLevelName] = {};
}

if (IsLastLevel(nextChoiceIndex)) {
if (currentLevel[nextLevelName] > 0) {
currentLevel[nextLevelName]++;
} else {
currentLevel[nextLevelName] = 1;
}
} else {
var goOneDeeper = nextChoiceIndex + 1;
HandleLevel(currentItem, currentLevel[nextLevelName], goOneDeeper);
}
}

var output = {};

for(var itemIndex in items)
{
var item = items[itemIndex];
HandleLevel(item, output, 0);
}

console.log(output);

JsFiddle Demo

关于javascript - 如何遍历对象并创建树对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20237536/

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