如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:18:26  来源:igfitidea点击:

How to create a map of records from a javascript raw object with Immutable.js?

javascriptimmutabilityimmutable.jsreviver-function

提问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);

imagesMapis 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 Imagerecord defined as:

我想创建一个包含记录的地图,例如使用Image定义为的记录:

var ImageRecord = Immutable.Record({ id: undefined, urls: undefined })

How can I have imagesMapas map of ImageRecords? 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 reviverthat 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())

http://jsbin.com/ronomibano/4/edit

http://jsbin.com/ronomibano/4/edit