将元素推送到不可变映射中

时间:2017-06-22 07:42:52

标签: javascript immutable.js

我有一个不可变的地图,我正在迭代一个数组,构建我想要推送到那个不可变地图的对象。这样做的适当方法是什么?这就是我所拥有的:

let arrayOfNames = ['John', 'Lisa'];

arrayOfNames.forEach(function(name) {
  let id = generateId();
  let newPerson = {
    id: id,
    name: name,
  };

  // people is the immutable map
  people.set(id, newPerson);
});

console.log(people)//这没有插入John或Lisa,因为人们是不可变的。

我知道如何插入一个并将其分配给一个新变量:

let newPeople = people.set('3', {id: 3, name: 'John'});

但是当我有一个循环要通过时我该怎么做呢?

2 个答案:

答案 0 :(得分:0)

您需要在循环内重新分配people

let people = ... // notice let not const

arrayOfNames.forEach(function(name) {
  let id = generateId();
  let newPerson = {
    id: id,
    name: name,
  };

  // people is the immutable map
  people = people.set(id, newPerson);
});



let people = new Immutable.Map();

['Alice', 'Jane'].forEach((name, id) => {
  people = people.set(id, {id, name})
})

console.log(people)

// or using reduce

const people2 = ['John', 'Peter'].reduce((map, name, id) => map.set(id, {id, name}), new Immutable.Map)

console.log(people2)

<script src="https://unpkg.com/immutable@3.8.1/dist/immutable.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

另一种方法是首先“准备”新人物地图,然后将其与现有地图合并。

像:

const newPeopleMap = Immutable.Map(['John', 'Lisa'].map(function(personName) {
    let id = generateId();
    let newPerson = {
        id: id,
        name: name,
    };

    return [id, newPerson];
}));

const newMergedPeopleMap = people.merge(newPeopleMap);

这样,你就不会放弃不变性,这就是你可能首先使用Immutable.js的原因。 ;)