Javascript为递归函数的中断条件迭代JSON

时间:2017-02-27 08:10:20

标签: javascript json recursion break

我不确定如何检查并创建此递归函数的中断条件。此功能冻结浏览器(似乎无休止地循环)。

我正在尝试根据列表对象中提供的数据生成一系列嵌套的无序列表。

这是小提琴:https://jsfiddle.net/mzckoc7s/

var list = {
    "primary": [{
        "item": "item 1"
    }, {
        "item": "item 2",
        "secondary": [{
            "item": "item secondary 1"
        }, {
            "item": "item secondary 2"
        }, {
            "item": "item secondary 3",
            "secondary": [{
                "item": "item inner secondary 1"
            }]
        }]
    }, {
        "item": "item 3"
    }]
}

function items( obj ) {
    var output = '<ul>';
    for ( i = 0; i < obj.length; i++ ) {
        output += '<li>' + obj[i].item + '</li>';
        if (typeof obj[i].secondary != 'undefined') {
            items( obj[i].secondary );
            break;
        }
    }
    output += '</ul>';
    return output;
}

最终结果应该是这样的:

<ul>
<li>item 1</li>
    <li>item 2
        <ul>
            <li>item secondary 1</li>
            <li>item secondary 2</li>
            <li>item secondary 3
                <ul>
                    <li>item inner secondary 1</li>
                </ul>
            </li>
        </ul>
        </li>
    <li>item 3</li>
</ul>

1 个答案:

答案 0 :(得分:1)

您可以使用嵌套方法迭代对象和possisble数组的键。然后建立输出并尊重没有给孩子。

function getItems(object) {
    var output = '';
    object && typeof object === 'object' && Object.keys(object).forEach(function (k) {
        if (k === 'item' || !object[k]) {
            return;
        }
        output = output || '<ul>';
        output += (Array.isArray(object[k]) ? object[k] : [object[k]]).map(function (a) {
            return '<li>' + a.item + getItems(a) + '</li>';
        }).join('');
    });
    output += output && '</ul>';
    return output;
}

var list = { primary: [{ item: "item 1" }, { item: "item 2", secondary: [{ item: "item secondary 1" }, { item: "item secondary 2" }, { item: "item secondary 3", secondary: { item: "item inner secondary 1" } }] }, { item: "item 3" }] },
    result = getItems(list); 

document.body.innerHTML = result;
.as-console-wrapper { max-height: 100% !important; top: 0; }