获取树对象属性
Sunny-117 opened this issue · comments
Sunny commented
var tree = {
name: '**',
children: [
{
name: '北京',
children: [
{
name: '朝阳群众'
},
{
name: '海淀区'
},
{
name: '昌平区'
}
]
},
{
name: '浙江省',
children: [
{
name: '杭州市',
code: '0571',
},
{
name: '嘉兴市'
},
{
name: '绍兴市'
},
{
name: '宁波市'
}
]
}
]
};
function fn(tree, name) {
//bfs
let Queue = [[tree.name, tree.children]];
while (Queue.length > 0) {
//出队当前节点
let cur = Queue.shift();
if (cur[0] === name) return { name: name, code: cur[1] }
//将children入队
if (cur.length === 1) continue;
for (let node of cur[1]) {
let obj = [node.name];
if (node.hasOwnProperty("children")) obj.push(node.children);
if (node.hasOwnProperty("code")) obj.push(node.code);
Queue.push(obj);
}
}
return -1;
}
var node = fn(tree, '杭州市');
console.log(node); // { name: '杭州市', code: 0571 }
CSC66666 commented
gettreenodeDeep(tree, name) {
const res = {}
const dfs = (tree, name) => {
if(!tree) {
return
}
if(tree.name === name) {
res.name = tree.name
res.code = tree.code
return
}
if(tree.children) {
for(let item of tree.children) {
dfs(item, name)
}
}
}
dfs(tree, name)
return res
}``
kangkang123269 commented
输入name,找code
function getCode(tree, cityName) {
if (tree.name === cityName) {
return tree.code || null;
} else if (tree.children) {
for (var i = 0; i < tree.children.length; i++) {
var code = getCode(tree.children[i], cityName);
if (code) {
return code;
}
}
}
return null;
}
Lesenelir commented
function getCode(tree, name) {
let res = {}
traversal(tree)
return res
function traversal(node) {
if (!node) return
if (node.name === name) {
res = {...node}
return
}
node.children && node.children.forEach(item => {
traversal(item)
})
}
}
console.log(getCode(tree, '杭州市')) // { name: '杭州市', code: '0571' }