Aleksandar Seferinkin
Aleksandar Seferinkin

Reputation: 63

How can i create deeply nested List in Map using Immutable JS Map.setIn?

I need to create Lists at some point using Map.setIn method. The problem is that when i specify indexes in the path it does not understand that i am working with List. The following example does not work:

let data = new Map().setIn(['person', 'products', 0, 'isAvailable'], true);
List.isList(data.getIn(['person', 'products'])) // Returns false because it is Map instance

So, how can i tell Immutable JS that 'products' in my case must be List instead of Map? I can't initialize the Map in my case, because the structure is very dynamic and the path may vary.

Upvotes: 2

Views: 480

Answers (1)

AlexMorley-Finch
AlexMorley-Finch

Reputation: 6975

The above syntax you provided is correct, but only if "person.products" is already a list. E.G.

// In this example, `products` won't be a list
(new Map()).setIn(['person', 'products', 1, 'isAvailable'], true)


// In this example, `products` will be a list
var initial = new Map({
  person: {
    name: '',
    products: [{isAvailable: true}, {isAvailable: false}]
  }
})

initial.setIn(['person', 'products', 1, 'isAvailable'], true)

This is the only solution I could find.

You could always write your own setIn function that looks for integers and sets the value to a new List()

Upvotes: 2

Related Questions