深度克隆对象无法运行-javascript

时间:2019-04-10 18:26:08

标签: 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)

0 个答案:

没有答案