在Immutable.js中获取嵌套值 [英] Getting nested values in Immutable.js

查看:55
本文介绍了在Immutable.js中获取嵌套值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这里的文档: https://facebook.github.io/immutable-js / docs /#/ map / getIn

我应该能够通过为 keyPath提供一个数组来获得深度嵌套的值参数。这就是我所做的,但是我得到 undefined 作为返回值。

I should be able to get the deeply nested value by providing an array for the keyPath argument. This is what I've done, however I'm getting undefined as the return value.

http://jsfiddle.net/srxv4mwu/

var obj = Immutable.Map({categories: {1: 'a', 2: 'b'}});
var output = obj.getIn(['categories', 1]);
alert(output);

我做错了什么?

推荐答案

地图只是一组带有值的键。你所拥有的是一张带有键的地图,以及价值 {1:'a',2:'b'} 。该值不会自动成为不可变地图,因为您将其放在另一个地图中。

A map is simply a collection of keys with values. What you have is a map with the key categories, and the value {1: 'a', 2: 'b'}. The value does not automatically become an Immutable map just because you place it inside another map.

现在, getIn() function只会看到其他Immutable.js地图。你在那里有一个常规的ol'javascript对象。如果您只想获得 1 值,您可以这样做:

Now, the getIn() function will only "see" other Immutable.js maps. What you have in there is a regular ol' javascript object. If you just want to get the 1 value, you can just do:

var obj = Immutable.Map({categories: {1: 'a', 2: 'b'}});
var output = obj.getIn(["categories"])[1];
alert(output);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

如果您希望类别集合也是地图,你必须明确地定义它。另外,正如Amit指出的那样,你需要使用带有 getIn()函数的字符串。

If you want the categories collection to also be a map, you'll have to define that explicitly. Also, as Amit pointed out, you'll need to use strings with the getIn() function.

var obj = Immutable.Map({
	categories: Immutable.Map({
		1: 'a',
		2: 'b'
	})
});
var output = obj.getIn(['categories', '1']);
alert(output);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

以上代码将返回'a '

如果您有许多嵌套地图,那么您可能会更方便地执行以下操作。

It would probably be more convenient for you to do something like below, if you have many nested maps.

var obj = Immutable.fromJS({
	categories: {
		1: 'a',
		2: 'b'
	}
});
var output = obj.getIn(['categories', '1']);
alert(output);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

fromJs() function会自动将任何嵌套对象转换为地图或列表。

The fromJs() function will convert any nested objects into maps or lists automatically for you.

这篇关于在Immutable.js中获取嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆