如何遍历Object并创建树对象

Din*_*ler 5 javascript loops object

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

choices: ['choice1', 'choice2', 'choice3'];
items: [
    {
        choice1: 'taste',
        choice2: 'good',
        choice3: 'green-lemon'
    },
    {
        choice1: 'taste',
        choice2: 'bad',
        choice3: 'green-lemon'
    }
];
Run Code Online (Sandbox Code Playgroud)

该数组描述了每个选择在树中的级别.我不知道以后会有多少选择,项目或级别.

如何获取以下对象:

output: {
    taste: {
        good: {
            green-lemon:1
        },
        bad: {
            green-lemon:1
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

有关如何构建循环以获得此结果的任何建议?

Dr *_*ang 2

我认为这里最好的解决方案是带有一些递归的循环。我增加了示例中模型的大小,以显示它具有 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);
Run Code Online (Sandbox Code Playgroud)

JsFiddle 演示