javascript递归链接对象以构建对象树

时间:2016-07-04 22:12:03

标签: javascript

我有两个看起来像这样的对象:

var cache = {
 '39' : { id : 39, name : 'Tom' },
 '40' : { id : 40, name : 'David'},
 '41' : { id : 41, name : 'Daniel'},
 '356': { id :356, grp: 'ROM', fee: '$35'} 
}

var tree = {
 person : { id : 39 },
 memberships : { id : 356 },
}

我尝试做的是编写一个递归函数,将tree对象作为参数,并生成一个引用/链接到{{1}中相应对象的数据结构对象。所以最后我必须能够访问用户' Tom'像这样:cache

我使用递归有两个原因:

  1. 我的实际tree.person.name对象比我在这里显示的更复杂(它是嵌套的)
  2. 根据用户输入和树的深度未知,它会有所不同
  3. 我编写了这个递归函数来进行引用/链接:

    tree

    然后我调用函数

    var traverse = function (jsonObj) {
        if( typeof jsonObj == "object" ) { 
            if(cache[jsonObj.id]){
              jsonObj = Ocache[jsonObj.id];
    
          }
          $.each(jsonObj, function(k, v) {
            traverse(v);
          });
        }
        else {
            // jsonObj is a number or string
        }
      }
    

    但是当我使用调试器查看我的 traverse(tree); 对象时,没有任何变化:tree与之前相同。如何在缓存对象中实现此目标和引用/链接对象?

1 个答案:

答案 0 :(得分:1)

代码中的主要问题是jsonObj = cache[jsonObj.id]:在这里,您要覆盖jsonObj traverse中的局部变量,这对此特定函数之外的任何内容都没有影响调用

为了更改嵌套树对象本身,您必须跟踪父对象和当前键:



var cache = {
    '39' : { id: 39, name: 'Tom' },
    '40' : { id: 40, name: 'David'},
    '41' : { id: 41, name: 'Daniel'},
    '356': { id: 356, grp: 'ROM', fee: '$35'} 
};

var tree = {
    person: { id: 39 },
    memberships: { id: 356 },
};

function traverse(obj) {
    for (var k in obj) {
        var v = obj[k];
        if (!v || typeof v !== 'object') continue;
        if (cache[v.id]) {
            obj[k] = cache[v.id];
        } else {
            traverse(v);
        }
    }
}

traverse(tree);

console.log(tree);




我添加了!v支票,因为typeof nullobject,但我们不想递归到null

我没有确定没有id的对象被视为拥有id: 'undefined'(如果您不想要,请在if (cache[v.id])行添加额外的支票)