使用for循环使用不可变的js构建深层对象

时间:2018-08-31 12:11:34

标签: javascript immutable.js

我正在尝试使用immutable-js构建对象,以构建较小的对象,然后将其合并到较大的对象中。

这是我尝试过的:

let globalObject = Immutable.Map({});
let keys = ["a","b","c"];
let newKeys = ["x","y","z"];
const objThing = { "q": 77 };
let newGlobalObject = globalObject.setIn(keys, objThing);

for (let i = 0; i < 3; i++) {
  const original = newGlobalObject.getIn(['a', 'b']);
  const newKey = newKeys[i];
  const newObject = {};
  newObject[newKey] = i;
  const mergedObject = original.merge(newObject);
  globalObject = newGlobalObject.updateIn(['a', 'b'], val => {
    return mergedObject
  });
}

console.log(JSON.stringify(globalObject));

但是,输出是

{
  "a": {
    "b": {
      "c": {
        "q": 77
      },
      "z": 2
    }
  }
}

我希望它是

{
  "a": {
    "b": {
      "c": {
        "q": 77
      },
      "x": 0,
      "y": 1,
      "z": 2
    }
  }
}

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

好,所以我想找到了答案。

我还不会将其标记为问题的答案,因为我想让其他人有机会发布更好的答案...仅仅因为这有效并不意味着它是正确的;)

我正在创建一个名为newGlobalObject的新变量来存储数据,因为我认为仅使用globalObject是错误的,因为那样会使事情发生变化。但事实证明,这正是我要做的。

let globalObject = Immutable.Map({});
let keys = ["a", "b", "c"];
let newKeys = ["x", "y", "z"];
const objThing = {
  "q": 77
};
globalObject = globalObject.setIn(keys, objThing);

for (let i = 0; i < 3; i++) {
  const original = globalObject.getIn(['a', 'b']);
  const newKey = newKeys[i];
  const newObject = {};
  newObject[newKey] = i;
  const mergedObject = original.merge(newObject);
  globalObject = globalObject.updateIn(['a', 'b'], val => {
    return mergedObject
  });
}

console.log(globalObject.toJs());

输出:{"a":{"b":{"c":{"q":77},"x":0,"y":1,"z":2}}}