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);
function jsonToArray(nodes) {
var r=[];
if (Array.isArray(nodes)) {
for (var i=0, l=nodes.length; i<l; i++) {
r.push(nodes[i]); // 取每项数据放入一个新数组
if (Array.isArray(nodes[i]["childs"])&&nodes[i]["childs"].length>0)
// 若存在children则递归调用,把数据拼接到新数组中,并且删除该children
r = r.concat(jsonToArray(nodes[i]["childs"]));
delete nodes[i]["childs"]
}
}
return r;
}
jsonToArray(tree)