日期:2014-05-16  浏览次数:20413 次

json递归问题
var nodes = [
{ "id": 2, "title": "江苏", "parentid": 0 },
{ "id": 3, "title": "无锡", "parentid": 2 },
{ "id": 4, "title": "常州", "parentid": 2 },
{ "id": 5, "title": "金坛", "parentid": 4 },
{ "id": 6, "title": "宜兴", "parentid": 3 },
{ "id": 7, "title": "温州", "parentid": 9 },
{ "id": 8, "title": "杭州", "parentid": 9 },
{ "id": 9, "title": "浙江", "parentid": 0}
]

以上格式数据N条,我想获得id=2 即江苏下面所有地区,包括地级市及下属区县格式数据,结果如下:
{ "id": 2, "title": "江苏", "parentid": 0 },
{ "id": 3, "title": "无锡", "parentid": 2 },
{ "id": 4, "title": "常州", "parentid": 2 },
{ "id": 5, "title": "金坛", "parentid": 4 },
{ "id": 6, "title": "宜兴", "parentid": 3 },

请问用js或者jquery怎么获取以上数据

------解决方案--------------------
JScript code

var nodes = [
{ "id": 2, "title": "江苏", "parentid": 0 },
{ "id": 3, "title": "无锡", "parentid": 2 },
{ "id": 4, "title": "常州", "parentid": 2 },
{ "id": 5, "title": "金坛", "parentid": 4 },
{ "id": 6, "title": "宜兴", "parentid": 3 },
{ "id": 7, "title": "温州", "parentid": 9 },
{ "id": 8, "title": "杭州", "parentid": 9 },
{ "id": 9, "title": "浙江", "parentid": 0}
];
var Node=function(obj){
    for(var p in obj)this[p]=obj[p];
    this._children=[];
};
Node.prototype={
    _addChild:function(node){
        this._children.push(node);
    },
    _getRaw:function(){
        var o={};
        for(var p in this)if(this.hasOwnProperty(p) && p!='_children')o[p]=this[p];
        return o;
    }
};

var Map=function(){
    this._keys=[];
};
Map.prototype={
    _containsKey:function(k){
        if(this.hasOwnProperty(k))return true;
        return false;
    },
    _put:function(k,v){if(!this._containsKey(k))this._keys.push(k);this[k]=v},
    _get:function(k){return this[k];}
};

var ns=new Map(),root,n,ids;
for(var i=nodes.length-1;i>=0;i--){
    n=new Node(nodes[i]);
    ns._put(n.id,n);
    if(n.id==2)root=n;
}

ids=ns._keys;
for(var i=ids.length-1;i>=0;i--){
    n=ns._get(ids[i]);
    if(!n)continue;
    if(ns._containsKey(n.parentid))ns._get(n.parentid)._addChild(n);
}
//经过上面的处理,root是一个树的根节点,root本身是id=2的那个记录,如果要获取所有的记录而不是树,请继续:
ns=[];
var getAll=function(node){
    ns.push(node._getRaw());
    for(var cs=node._children,i=0,il=cs.length;i<il;i++)getAll(cs[i])
}
getAll(root);
//到此ns为所有符合要求的记录集
for(var i=0,il=ns.length;i<il;i++)alert(ns[i].id)

------解决方案--------------------
var nodes = [
{ "id": 2, "title": "江苏", "parentid": 0 },
{ "id": 3, "title": "无锡", "parentid": 2 },
{ "id": 4, "title": "常州", "parentid": 2 },
{ "id": 5, "title": "金坛", "parentid": 4 },
{ "id": 6, "title": "宜兴", "parentid": 3 },
{ "id": 7, "title": "温州", "parentid": 9 },
{ "id": 8, "title": "杭州", "parentid": 9 },
{ "id": 9, &