Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Immutable.fromJS()没有将我的JSON深度转换为不可变对象_Javascript_Immutable.js - Fatal编程技术网

Javascript Immutable.fromJS()没有将我的JSON深度转换为不可变对象

Javascript Immutable.fromJS()没有将我的JSON深度转换为不可变对象,javascript,immutable.js,Javascript,Immutable.js,我有两个给定的不可变列表,我将它们连接起来,如下所示: const fruits = Immutable.List(['apple', 'banana']); const vegetables = Immutable.List(['carrot']); const groceries = fruits.concat(vegetables); 我使用map函数转换数据以获得对象列表,最后使用fromJS将其转换为immutable,如下所示: const result = groceries.m

我有两个给定的不可变列表,我将它们连接起来,如下所示:

const fruits = Immutable.List(['apple', 'banana']);
const vegetables = Immutable.List(['carrot']);
const groceries = fruits.concat(vegetables);
我使用map函数转换数据以获得对象列表,最后使用fromJS将其转换为immutable,如下所示:

const result = groceries.map((item, index) => ({ id: index, item }));
const checkList = Immutable.fromJS({ groceries: result });
{
  groceries: <Immutable List>
}
{ id: 0, item: 'apple'}
因此,最终数据是给定JSON的不可变对象:

   {
      "groceries": [
        {
          "id": 0,
          "item": "apple"
        },
        {
          "id": 1,
          "item": "banana"
        },
        {
          "id": 2,
          "item": "carrot"
        }
      ]
    }
我期望fromJS将对象
{groceries:result}
深深地转换为不可变对象。但是当我检查checkList.getIn(['groceries',0'])的值时,我得到一个普通的JSON对象
{id:0,item:'apple`}
,而不是预期的不可变映射


有人能帮我解释一下为什么会发生这种情况吗引用immutableJS repo中的语句

Immutable.fromJS()在转换时是保守的。它只将普通对象(无自定义原型)转换为Immutable.Map,将true数组转换为Immutable.List。这确保了外来对象(日期对象、DOM节点、用户定义的类型)不会无意中转换为Immutable.Map

因此它只转换普通对象。在使用
fromJS
之前的情况下,数据如下所示:

const result = groceries.map((item, index) => ({ id: index, item }));
const checkList = Immutable.fromJS({ groceries: result });
{
  groceries: <Immutable List>
}
{ id: 0, item: 'apple'}
fromJS
将数据转换为不可变数据,直到它遇到普通对象和真正数组以外的任何对象。这就是为什么它没有转换不可变列表中的元素,因为它不是真数组

您的问题可以通过将
fromJS
添加到下面的代码中来解决

const result = groceries.map((item, index) => fromJS({ id: index, item }));