js json 树转json方法

时间:2019-07-04
本文章向大家介绍js json 树转json方法,主要包括js json 树转json方法使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

var tree = [{
            id: "parent",
            parentId: "",
            name: "一级节点",
            childs: [{
                id: "child1",
                parentId: "parent",
                name: "一级节点",
                childs: []
            }, {
                id: "child2",
                parentId: "parent",
                name: "一级节点",
                childs: []
            }]
        }]

        function adsa(tree, key) {
            return tree.reduce(function(con, item) {
                var callee = arguments.callee;
                con.push(item);
                if(item[key] && item[key].length > 0) item[key].reduce(callee, con);
                return con;
            }, []).map(function(item) {
                item[key] = [];
                return item;
            })
        }
        var arr = adsa(tree, 'childs'); //输出转换后数组
        console.log(arr);

原文地址:https://www.cnblogs.com/zyb-722/p/11134159.html