3 回答
TA贡献1851条经验 获得超5个赞
您可以ids通过在实际级别查找对象来迭代对象并减少对象。如果没有找到创建一个新对象。然后让孩子们回来。
var data = [{ id: '1:2:6', ids: ['1', '2', '6'] }, { id: '1:4', ids: ['1', '4'] }, { id: '1', ids: ['1'] }, { id: '1:2', ids: ['1', '2'] }],
tree = data.reduce((r, { ids }) => {
ids.reduce((t, _, i, a) => {
var id = a.slice(0, i + 1).join(':'),
temp = t.find(o => o.id === id);
if (!temp) t.push(temp = { id, children: [] });
return temp.children;
}, r);
return r;
}, []);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1801条经验 获得超16个赞
使用递归算法构建树
var jsonTree = [{ id: '1:2:6', ids: ['1', '2', '6'] },{ id: '1:4', ids: ['1', '4'] },{ id: '1', ids: ['1'] },{ id: '1:2', ids: ['1', '2'] },]
var newJsonTree = [];
var currentElement = {id: '1',childs: []}
newJsonTree.push(currentElement)
function buildTree(jsonTree, currentElement){
for(var i=0;i<jsonTree.length;i++){
var parent = jsonTree[i];
for(var j=0;j<jsonTree.length;j++){
var child = jsonTree[j];
if(child['visited'] != true && child['id'] != currentElement['id'] && child['id'].indexOf(currentElement['id']) == 0 ){
if(child['id'].split(":").length == currentElement['id'].split(":").length+1){
var newElement = {}
newElement['id'] = child['id'];
newElement['childs'] = [];
currentElement['childs'].push(newElement);
child['visited'] = true;
buildTree(jsonTree, newElement);
}
}
}
}
}
buildTree(jsonTree, currentElement);
document.write(JSON.stringify(newJsonTree));
结果:
[{"id":"1","childs":[{"id":"1:4","childs":[]},{"id":"1:2","childs":[ {"id":"1:2:6","childs":[]}]}]}]
添加回答
举报