javascript树数据源嵌套结构和扁平结构互转

  javascript树,嵌套结构数据源和扁平结构数据源相互转换示例

<title>javascript树数据源嵌套结构和扁平结构互转示例</title>
<script type="text/javascript">
    function FlatToNested(data, opt) {//树数据源扁平结构转嵌套
        opt = opt || {};
        var idFiled = opt.idFiled || 'id';
        var textFiled = opt.textFiled || 'text';
        var parentField = opt.parentField || 'parent';
        var i, l, treeData = [], tmpMap = [];
        for (i = 0, l = data.length; i < l; i++) tmpMap[data[i][idFiled]] = data[i];
        for (i = 0, l = data.length; i < l; i++) {
            if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
                if (!tmpMap[data[i][parentField]]['children'])
                    tmpMap[data[i][parentField]]['children'] = [];
                data[i]['text'] = data[i][textFiled];
                tmpMap[data[i][parentField]]['children'].push(data[i]);
            } else {
                data[i]['text'] = data[i][textFiled];
                treeData.push(data[i]);
            }
        }
        return treeData;
    }
    function NestedToFlat(children, parent) {//树数据源嵌套结构转扁平
        var arr = []
        for (var i = 0; i < children.length; i++) {
            arr.push({ id: children[i].id, text: children[i].text, parent: parent })
            if (children[i].children) arr = arr.concat(NestedToFlat(children[i].children, children[i].id));
        }
        return arr;
    }
    var data = [
        { "id": 1, "text": "text1", "children": [{ "id": 4, "text": "text1_1" }, { "id": 5, "text": "text1_2" }] },
        { "id": 2, "text": "text2", "children": [{ "id": 6, "text": "text2_1", "children": [{ "id": 7, "text": "text2_1_1" }] }] },
        { "id": 3, "text": "text3" }];
    data = NestedToFlat(data, 0);
    console.log(data);
    data = FlatToNested(data, 0);
    console.log(data);
</script>

 


原创文章,转载请注明出处:javascript树数据源嵌套结构和扁平结构互转

评论(0)Web开发网
阅读(202)喜欢(0)不喜欢(0)JavaScript/Ajax开发技巧