树的递归

zhx86890057 2017-12-02 09:13:38
{"id": 1,
"pid": 0,
"code": "310000",
"name": "浙江省",
"type": 0,
"memo": "",
"info": {},
"children": [
{
"id": 177,
"pid": 1,
"code": "",
"name": "温州市",
"type": 0,
"memo": "",
"info": {},
"children": []
},
{
"id": 3,
"pid": 1,
"code": "310000",
"name": "杭州市",
"type": 0,
"memo": "",
"info": {},
"children": [{
"id": 179,
"pid": 3,
"code": "",
"name": "西湖区",
"type": 0,
"memo": "",
"info": {},
"children": [
{"id": 179,
"pid": 179,
"code": "",
"name": "文一路",
"type": 0,
"memo": "",
"info": {},
"children": []}
]
}]
},{
"id": 11,
"pid": 1,
"code": "",
"name": "宁波市",
"type": 0,
"memo": "",
"info": {},
"children": []
}
]
}
这是json格式的树结构,比如:我想要取得id为179下面的children,采用递归怎么写啊。用js写一下,java也行。
...全文
85 1 点赞 打赏 收藏 举报
写回复
1 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
天际的海浪 2017-12-02

var obj = {
	"id": 1,
	"pid": 0,
	"code": "310000",
	"name": "浙江省",
	"type": 0,
	"memo": "",
	"info": {},
	"children": [{
		"id": 177,
		"pid": 1,
		"code": "",
		"name": "温州市",
		"type": 0,
		"memo": "",
		"info": {},
		"children": []
	}, {
		"id": 3,
		"pid": 1,
		"code": "310000",
		"name": "杭州市",
		"type": 0,
		"memo": "",
		"info": {},
		"children": [{
			"id": 179,
			"pid": 3,
			"code": "",
			"name": "西湖区",
			"type": 0,
			"memo": "",
			"info": {},
			"children": [{
				"id": 999,
				"pid": 179,
				"code": "",
				"name": "文一路",
				"type": 0,
				"memo": "",
				"info": {},
				"children": []
			}]
		}]
	}, {
		"id": 11,
		"pid": 1,
		"code": "",
		"name": "宁波市",
		"type": 0,
		"memo": "",
		"info": {},
		"children": []
	}]
}
function getById(g,n) {
	if (g.id==n) {
		return g.name;
	} else {
		for (var i = 0; i < g.children.length; i++) {
			var r = getById(g.children[i],n);
			if (r)
				return r;
		}
		return null;
	}
}
alert(getById(obj,999));
  • 打赏
  • 举报
回复
相关推荐
发帖
JavaScript
加入

8.5w+

社区成员

Web 开发 JavaScript
申请成为版主
帖子事件
创建了帖子
2017-12-02 09:13
社区公告
暂无公告