穿线

data = {
	"0": {
		"id": 1,
		"pid": 0,
		"children": [{
			"id": 2,
			"pid": 1,
			"children": [{
				"id": 5,
				"pid": 2
			}, {
				"id": 6,
				"pid": 2
			}, {
				"id": 7,
				"pid": 2
			}, {
				"id": 8,
				"pid": 2
			}, {
				"id": 126,
				"pid": 2
			}, {
				"id": 131,
				"pid": 2

			}, {
				"id": 132,
				"pid": 2
			}]
		}, {
			"id": 4,
			"pid": 1,
			"children": [{
				"id": 12,
				"pid": 4
			}, {
				"id": 110,
				"pid": 4
			}, {
				"id": 111,
				"pid": 4
			}]
		}, {
			"id": 122,
			"pid": 1,
			"children": [{
				"id": 123,
				"pid": 122
			}, {
				"id": 124,
				"pid": 122
			}, {
				"id": 125,
				"pid": 122
			}]
		}, {
			"id": 130,
			"pid": 1
		}]
	},
	"1": {
		"id": 117,
		"pid": 0,
		"children": [{
			"id": 555,
			"pid": 117,
			"children": [{
				"id": 119,
				"pid": 118
			}, {
				"id": 120,
				"pid": 118
			}, {
				"id": 121,
				"pid": 118
			}]
		}]
	},
	"2": {
		"id": 127,
		"pid": 0,
		"children": [{
			"id": 128,
			"pid": 127,
			"children": [{
				"id": 129,
				"pid": 128
			}]
		}]
	}
}

function foo(data) {
  for(var k in data) {
    line[data[k].id] = data[k];
    if(data[k].children) {
       foo(data[k].children);
    }
  }
}

function getParents(id) {
    var res = [];
    if(! line[id]) return res;
    res.push(line[id].id)
    return res.concat( getParents(line[id].pid) );
}

line = {};
foo(data); //穿线
r = getParents(131);
document.write(r.join(","));

 

posted @ 2018-12-11 19:36  郑家好人  阅读(149)  评论(0编辑  收藏  举报