Javascript 将元素推入不可变映射
我有一个不可变的映射,我在一个数组上迭代,构建我想要推进到那个不可变映射中的对象。这样做的适当方式是什么?以下是我所拥有的:Javascript 将元素推入不可变映射,javascript,immutable.js,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
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);
});
log(people)//这没有插入John或Lisa,因为人是不可变的
我知道如何插入一个变量并将其分配给新变量:
let newPeople=people.set('3',{id:3,name:'John'})代码>
但是,当我有一个循环要通过时,我该怎么做呢?您需要在循环内部重新分配人员
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((姓名,id)=>{
people=people.set(id,{id,name})
})
console.log(人)
//或者使用reduce
constpeople2=['John','Peter'].reduce((map,name,id)=>map.set(id,{id,name}),new Immutable.map)
console.log(people2)
另一种方法是首先“准备”新的人员地图,然后将其与现有地图合并
比如:
这样,您就不会放弃不变性,这就是为什么您可能首先使用Immutable.js的原因
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);