deep access in plain objects with Immutable

孤街浪徒 提交于 2019-12-12 19:30:32

问题


Consider the following example:

const stickers = 
  new OrderedMap().set(1, {hero: "batman", name: "Bruce"});

stickers.getIn([1]); //=> { hero: 'batman', name: 'Bruce' }

stickers.getIn([1, "hero"]); //=> undefined

Why is the result of that second getIn undefined?

The docs on ImmutableJS state:

Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and getIn() can access those values as well

Therefore, it follows that it makes no difference if value of the OrderedMap is a plain javascript object or an Immutable collection - however we can see that the bug goes away if we convert that plain object to an Immutable Collection first:

const stickers = 
  new OrderedMap().set(1, fromJS({hero: "batman", name: "Bruce"}));

stickers.getIn([1]); //=> { hero: 'batman', name: 'Bruce' }

stickers.getIn([1, "hero"]); //=> 'batman'

回答1:


I believe this is because you're looking at the docs for a newer version of the library than you're using. I just tried out your code with version 4.0.0-rc.9 and it works as expected.

For example:

const stickers =
  Immutable.OrderedMap().set(1, {
    hero: "batman",
    name: "Bruce"
  });

console.log(stickers.getIn([1]));

console.log(stickers.getIn([1, "hero"])); // 
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>


来源:https://stackoverflow.com/questions/49025635/deep-access-in-plain-objects-with-immutable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!