如何在深层嵌套对象中使用另一个对象引用设置一种类型的对象引用?
// Following is the class
class Ab{ a: number; }
let x = new Ab();
x.a = 10;
// Now I have an object something like this
let obj = {
b: 'hello',
c: new Ab(),
d: {
x: 5,
y: new Ab(),
z: {
p: new Ab()
}
}
}
现在我应该能够将新的Ab()设置的所有引用更改为x
对象。
let obj = {
b: 'hello',
c: x, // reassign the x reference
d: {
x: 5,
y: x,
z: {
p: x
}
}
}
我想我必须深入克隆这个对象。我正在使用lodash
lodash.cloneDeepWith(obj, val => {
// please do not worry/consider these logic this condition is working
if (Object.getPrototypeOf(val) === tc) {
// Actual problem is here
// reassigning is not changing the original reference of obj
val = x;
}
});
有没有更快更容易的解决方案?任何帮助表示赞赏。
答案 0 :(得分:1)
以下代码将根据实例类型递归更改每个对象:
const changeObjects = (obj, replacement, className) => {
Object.keys(obj).forEach((key) => {
if (obj[key] instanceof className) {
obj[key] = replacement;
} else if (typeof obj[key] === 'object') {
changeObjects(obj[key], replacement, className);
}
});
}
changeObjects(obj, x, Ab);
该代码应该与您提供的示例一起使用而不创建深度克隆。如果您确实想要克隆替换并且没有循环引用,那么您也可以这样做:
obj[key] = Object.assign({}, replacement);
分配替换时。
我不确定这是否更容易,但速度更快,完成了你需要做的工作。