我有两个看起来像这样的对象:
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
。
我使用递归有两个原因:
tree.person.name
对象比我在这里显示的更复杂(它是嵌套的)我编写了这个递归函数来进行引用/链接:
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
与之前相同。如何在缓存对象中实现此目标和引用/链接对象?
答案 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 null
是object
,但我们不想递归到null
。
我没有确定没有id
的对象被视为拥有id: 'undefined'
(如果您不想要,请在if (cache[v.id])
行添加额外的支票)