我有需要在对象上添加位置属性的 javascript 函数。
function conv(data){
var result=[];
function dfs(node, parent) {
for(var i in node){
result.push({id:node[i].id,pid:parent});
if (node[i]['children']) dfs(node[i]['children'],node[i]['id']);
}
}
dfs(data, 0);
return result;
}
所以我得到了结果=[{"id":1,"pid":0},{"id":4,"pid":1},{"id":2,"pid":0}]
需要添加类似的位置:
[
{"id":1,"pid":0,"position":100}, // First root
{"id":4,"pid":1,"position":100}, // First sub root
{"id":5,"pid":1,"position":101}, // Second sub root
{"id":2,"pid":0,"position":101}, // Second root
{"id":3,"pid":0,"position":102}, // Third root
]
更新
位置总是从 100 开始,所以它的 var 可以是静态的。