首页 > 解决方案 > 深度克隆对象不运行功能 - 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)

标签: javascript

解决方案


推荐阅读