我正在尝试创建一个对象,如果需要,该对象在创建时的键被创建为OrderedMaps。
即
OrderedMap().setIn(['users','subusers'], OrderedMap())
我想要什么
OrderedMap->users->OrderedMap()->subusers->OrderedMap()
我真正得到的是什么
OrderedMap->users->Map()->subusers->OrderedMap()
是否有任何简单的方法可以获得仅包含OrderedMaps的OrderedMap?
答案 0 :(得分:0)
不幸的是,所有whateverIn
函数都以updateIn
结尾,该函数使用emptyMap()
作为其notSetValue。我猜想添加一个类似于Immutable的fromJS的reviver函数将是一个好主意,并且可能被接受为Issue / Pull Request。
请注意,当您从头开始构建完整的树时,您可能只想将fromJS与自定义齐磊器一起使用。这是ImmutableJS文档中示例的副本:
const { fromJS, isKeyed } = require('immutable@4.0.0-rc.9')
fromJS({ a: {b: [10, 20, 30]}, c: 40}, function (key, value, path) {
console.log(key, value, path)
return isKeyed(value) ? value.toOrderedMap() : value.toList()
})
下面是一个更新程序函数,它改用OrderedMap。
let map = Immutable.OrderedMap({key0:Immutable.OrderedMap()}).setIn(['key0','key1', 'key2', 'key3'], 'banana');
function check(what, name) {
console.log('verify map using', name);
let entry = what.entrySeq().first();
while(entry) {
if (Immutable.isImmutable(entry[1])) {
console.log(`${entry[0]} is ${Immutable.isOrdered(entry[1]) ? '' : 'un'}ordered`);
entry = entry[1].entrySeq().first();
} else {
console.log(`${entry[0]} = ${entry[1]}` );
entry = null;
}
}
}
check(map, 'setIn');
function orderedUpdateIn(what, path, value) {
if (what.has(path)) {
return what.setIn(path, value);
}
let missingPath = [], existingPath = [];
let pathMap = what;
// figure out what part is missing
for (let i = 0;i < path.length; i++) {
pathMap = pathMap.get(path[i]);
if (!pathMap) {
missingPath = path.slice(i);
existingPath = path.slice(0,i);
break;
}
}
// build missing part
let valueToSet = Immutable.OrderedMap({
[missingPath[missingPath.length - 1]]: value
});
for (let i = missingPath.length - 1;i >= 0; i--) {
valueToSet = Immutable.OrderedMap({
[missingPath[i]]: valueToSet
});
}
return map.setIn(existingPath, valueToSet);
}
map = orderedUpdateIn(Immutable.OrderedMap({key0:Immutable.OrderedMap()}), ['key0','key1', 'key2', 'key3'], 'banana');
check(map, 'updateIn');
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.12/immutable.js"></script>