javascript - 深度克隆对象不运行功能 - javascript
问题描述
我正在尝试克隆一个使用 npm deep-freeze 冻结的对象,但该函数不会再次自行运行。
我试图运行if(typeof === "object")
, 其次是Object.assign
, 但这给了我
typeError:无法分配给只读属性
function updateTree(tree, id, values) {
const treeData = JSON.parse(JSON.stringify(tree));
const dataKeys = Object.keys(tree[id]);
for (let property in treeData) {
if (property === treeData[id].id) {
dataKeys.forEach(key =>
key in values ? Object.assign(treeData[id], values) : null
);
if (treeData[id].children.length >= 1) {
treeData[id].children.map(childId =>
updateTree(treeData, childId, values)
);
}
}
}
return treeData;
}
test("update child nodes", t => {
const tree = freeze({
"1": {
id: "1",
foo: "",
baz: "",
children: ["2", "3"]
},
"2": {
id: "2",
foo: "",
baz: "",
children: ["4", "5"]
},
"3": {
id: "3",
foo: "",
baz: "",
children: ["6"]
},
"4": {
id: "4",
foo: "",
baz: "",
children: ["7"]
},
"5": {
id: "5",
foo: "",
baz: "",
children: []
},
"6": {
id: "6",
foo: "",
baz: "",
children: []
},
"7": {
id: "7",
foo: "",
baz: "",
children: []
}
});
updateTree(tree, "2", {
foo: "bar",
baz: "qux"
})
预期结果是函数 updateTree() 运行,因此函数是递归的
updateTree(treeData, childId, values)
解决方案
推荐阅读
- sql - 带有包含二进制数据的 WHERE 子句的 SQL 查询
- javascript - 循环块后Javascript json对象为空
- javascript - 无法访问使用 React.lazy 导入的组件的静态属性
- azure-api-management - APIM 处于消费模式 - 通过 /status-0123456789abcdef 获取 Azure APIM 运行状况检查返回“找不到资源”
- deep-learning - 在与图像翻译非常相似的任务中,如何处理 UNet 编码器/解码器 CNN 中的严重过拟合?
- asynchronous - 如何编写一个需要消费者将切片的内容memcpy到自己的分配中的流?
- amazon-web-services - AWS ALB - 如果重新创建底层 ALB,是否需要新证书?
- c# - 如何从 c# 控制台应用程序中的用户输入创建多个对象?
- node.js - 如何在 browserstack 中找到当前可用于测试的移动设备
- c# - 如何在字节数组C#中转换具有随机长度的字符串