动态更改不可变映射中的键的最佳方法是什么?
// I have a map like this:
const names = Map({
rya: true,
mike: false,
});
// I receive this as inputs
const inputIndex = 0;
const inputLetter = n;
// What are the operations that i need to do here to get the expected output
// [?CODE?]
// I expect this as output:
const names = Map({
ryan: true,
mike: false,
});
到目前为止,我的解决方案似乎效率很低:
const namesEntrySeq = names.entrySeq();
const objectToModify = namesEntrySeq.get(inputIndex);
objectToModify[0] = objectToModify[0] + inputLetter;
const namesAsArray = namesEntrySeq.toArray();
namesAsArray[inputIndex] = objectToModify;
const names = Immutable.Map(namesAsArray);
必须有更优雅的方式吗?
最佳答案
如果您依赖于 map 中实体的顺序保持不变,则应该使用 OrderedMap
,或者像Rafael said那样做并自己跟踪订单。
如果您使用 OrderedMap
,则可以使用 #mapEntries
更新其中的 key :
const names = Immutable.Map({
rya: true,
mike: false,
});
const letterToAdd = 'n';
const indexToUpdate = 0;
const updatedNames = names.mapEntries(([key, value], index) => {
if (index === indexToUpdate) {
return [key + letterToAdd, value];
} else {
return [key, value];
}
});
console.log(updatedNames);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>
请注意,这是低效的,因为它将迭代映射中的每个条目以更改条目。如果您的 map 很小,这可能并不重要。
<小时/>顺便说一句,您存储此数据的方式似乎不利于您想要修改它的方式。我会考虑重组您的数据,以便更轻松地对其执行您想要的操作类型。
关于javascript - 更改不可变映射中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846392/