I'm new to immutable.js and I'd like to understand better how to use records starting from a raw JS object.
With Immutable.fromJS()
I can create a map passing a raw object, for example:
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.
I'd like instead to create a map containing records, for example using a Image
record defined as:
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?
// old approach
var imagesMap = Immutable.Map()
for (key in images) {
imagesMap.set(key, new ImageRecord(images[key]))
}
Immutable.fromJS has 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.http://jsbin.com/ronomibano/4/edit