如何使用 Immutable.js 从 javascript 原始对象创建记录映射?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28639878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a map of records from a javascript raw object with Immutable.js?
提问by gpbl
I'm new to immutable.js and I'd like to understand better how to use records starting from a raw JS object.
我是 immutable.js 的新手,我想更好地了解如何使用从原始 JS 对象开始的记录。
With Immutable.fromJS()
I can create a map passing a raw object, for example:
随着Immutable.fromJS()
我可以创建一个地图将原料对象,例如:
var images = {
"1": {
id: "1",
urls: ["/medium/1.jpg", "/large/1.jpg"]
},
"2": {
id: "2",
urls: ["/medium/1.jpg", "/large/1.jpg"]
}
}
var imagesMap = Immutable.fromJS(images);
imagesMap
is now a map containing other maps, one for each image.
imagesMap
现在是一张包含其他地图的地图,每个图像一个。
I'd like instead to create a map containing records, for example using a Image
record defined as:
我想创建一个包含记录的地图,例如使用Image
定义为的记录:
var ImageRecord = Immutable.Record({ id: undefined, urls: undefined })
How can I have imagesMap
as map of ImageRecord
s? Is something I can do passing a reviver to fromJS
, or should I go with the "old" approach?
我怎么能有s的imagesMap
地图ImageRecord
?我可以做些什么来将复活者传递给fromJS
,还是应该采用“旧”方法?
// old approach
var imagesMap = Immutable.Map()
for (key in images) {
imagesMap.set(key, new ImageRecord(images[key]))
}
回答by OlliM
Immutable.fromJShas an optional second parameter reviver
that you can use. You just need to decide which parts of the js object you want to turn into records.
Immutable.fromJS有一个reviver
你可以使用的可选的第二个参数。您只需要决定要将 js 对象的哪些部分变成记录。
var images = {
"1": {
id: "1",
urls: ["/medium/1.jpg", "/large/1.jpg"]
},
"2": {
id: "2",
urls: ["/medium/1.jpg", "/large/1.jpg"]
}
};
var ImageRecord = Immutable.Record({ id: "0", urls: [] })
var imagesMap = Immutable.fromJS(images, function(key, value) {
// This check should be replaced by a better way to know that
// we really want image records
if(/^[0-9]+$/.test(key)) {
return new ImageRecord(value)
}
return value
});
// Verify that it's really a record
console.log(imagesMap.get("2").toJS())
console.log(imagesMap.get("2").delete("urls").toJS())