首页 > 解决方案 > 使用递归函数进行对象转换

问题描述

我有一个看起来像这样的对象:

{
    parent: {
        child1: {
            key: 'value'
        },
        child2: {
            key: 'value'
        },
        child3: {
            key: 'value'
        }
    }
}

我需要将其转换为如下所示的对象:

{
    title: 'parent',
    children: [{
        title: 'child1',
        children: [{
            title: 'key',
            value: 'value'
         }]
     }, {
        title: 'child2',
        children: [{
            title: 'key',
            value: 'value'
         }]
     }, {
        title: 'child3',
        children: [{
            title: 'key',
            value: 'value'
         }]
    }]
}

我最终得到了以下功能:

function transform(obj) {
    const result = {
        title: '',
        children: []
    };
    for (let key in obj) {
        let child = obj[key];
        result.title = key;
        if (typeof(child) === 'string') {
            delete result.children;
            result.value = child;
        } else {
            result.children.push(transform(child));
        }
    }
    return result;
}

但是当我运行它时,它会返回以下输出,这是错误的:

{
    title: 'parent',
    children: [{
        title: 'child3',
        children: [
            { title: 'key', value: 'value' },
            { title: 'key', value: 'value' },
            { title: 'key', value: 'value' }
        ]
    }]
}

谁能指出我在函数中的错误到底是什么?

标签: javascriptrecursion

解决方案


我认为您为树递归选择了错误的基本情况。将叶子检测放在函数的顶部,而不是在循环中:

function transform(title, value) {
    if (typeof value === 'string') {
        return {title, value};
    } else {
        const children = [];
        for (let key in obj) {
            children.push(transform(key, obj[key]));
        }
        return {title, children};
    }
}

由于您只想要根节点的单个子节点,因此您可以将其称为

console.log(transform('parent', data.parent));

或者

console.log(transform('', data).children[0]);

推荐阅读