Reputation: 309
I have 2 given immutable lists and I am concatenating them as follows:
const fruits = Immutable.List(['apple', 'banana']);
const vegetables = Immutable.List(['carrot']);
const groceries = fruits.concat(vegetables);
I used map function to transform data to get list of objects and finally converted it to immutable using fromJS like below:
const result = groceries.map((item, index) => ({ id: index, item }));
const checkList = Immutable.fromJS({ groceries: result });
So the final data is the immutable object of the given JSON:
{
"groceries": [
{
"id": 0,
"item": "apple"
},
{
"id": 1,
"item": "banana"
},
{
"id": 2,
"item": "carrot"
}
]
}
I expect fromJS would deeply convert the object { groceries: result }
to immutable object. But when I check the value of checkList.getIn(['groceries', '0'])
I get a plain JSON object {id: 0, item: 'apple`}
instead of the expected immutable map.
Can someone help me out why this happens
Upvotes: 1
Views: 1338
Reputation: 677
Quoting the statements in immutableJS repo
Immutable.fromJS() is conservative in its conversion. It only converts plain Objects (no custom prototype) to Immutable.Map and true Arrays to Immutable.List. This ensures that exotic objects (Date objects, DOM nodes, user-defined types) don't get converted to Immutable.Map unintentionally.
So it converts only plain Objects. In your case before fromJS
is used the data looks like below:
{
groceries: <Immutable List>
}
And within the list, each element is stored as plain JSON object like below:
{ id: 0, item: 'apple'}
fromJS
converts your data to immutable until it encounters anything other than plain Objects and true Arrays. That's why it didn't convert the elements in the immutable list as it is not true Array.
Your problem could be solved by adding fromJS
to the below code
const result = groceries.map((item, index) => fromJS({ id: index, item }));
Upvotes: 2