Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

Safely access nested value in Immutable.js structure

I'm considering introducing Immutable JS in an existing React project. The project is littered with deeply nested references, wrapped with the selectn utility.

For example:

// returns order.id or undefined if product or order or id are undefined
if(selectn('product.order.id',this.state)) {
  //...
}

Is there an Immutable JS API method to check a deeply nested structure, and return either the requested property or undefined?

Upvotes: 1

Views: 611

Answers (1)

kevin628
kevin628

Reputation: 3526

Here's an example.

var t = Immutable.fromJS({a: { aa: { aaa: 'thing' } } });

I want a.aa.aaa.

t.getIn(['a','aa','aaa']);
// returns "thing"

What if I try to get a.aa.bbb?

t.getIn(['a', 'aa', 'bbb']);
// Returns undefined.

Here's the API for getIn(): getIn() API.

Upvotes: 3

Related Questions