var sample = [{
"_id": "1",
"category": "type1",
"path": "data1//data2//data3//data4",
"org": "001"
},
{
"_id": "2",
"category": "type2",
"path": "data1//data2//data3//data4",
"org": "002"
}
];
以上样本数据需要转换为层次结构。
var sample = {
children: [{
name: "type1",
children: [{
name: "data1",
children: [{
name: "data2",
children: [{
name: "data3",
children: [{
name: "data4"
}]
}]
}]
}]
},
{
name: "type2",
children: [{
name: "data1",
children: [{
name: "data2",
children: [{
name: "data3"
}]
}]
}]
}
]
};
预期产出:
+type1
data1
data2
data3
data4
答案 0 :(得分:0)
您可以使用哈希表和层次结构来分配嵌套结构的子级别,并可以通过类别或路径值进行访问。
基本上这个提议检查一个键,如果不在对象中,则创建一个具有单个属性和子节点数组的新对象,以及一个新对象与父下划线数组相同引用前一个创建数组的数组。
然后返回实际级别。最后,使用lanst值创建objetc并将其推送到数组。
var sample = [{ _id: "1", category: "type1", path: "data1//data2//data3//data4", org: "001" }, { _id: "2", category: "type2", path: "data1//data2//data3//data4", org: "002" }],
result = { children: [] };
sample.forEach(function (a, i) {
var keys = [a.category].concat(a.path.split('//')),
last = keys.pop();
keys.reduce(function (r, k) {
if (!r[k]) {
r[k] = { _: [] };
r._.push({ name: k, children: r[k]._ });
}
return r[k];
}, this)._.push({ name: last });
}, { _: result.children });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }