Reputation: 13125
I'm introducing Immutable.js into my redux/react project. I'm changing the likes of:
let {id, name} = user;
to:
let id = user.get('id');
let name = user.get('name');
That's twice as much code. Is there any way of coding the latter in a more concise manner?
Upvotes: 1
Views: 79
Reputation: 432
You can not use destructuring with an Immutable.js Map
, at least not right out of the box. If your project uses Babel, you can add a plugin called babel-plugin-extensible-destructuring.
After configuring that, you'll be able to use destructuring and something like this will work:
import {fromJS} from 'immutable';
const map = fromJS({author: {name: {first: "John", last: "Doe"}, birthdate: "10-10-2010"}});
const {author: {name: {first, last}, birthdate}} = map;
Also, note that something like List
is an iterable and therefore can be destructured like a regular array.
For example:
const list = List(['Hello', 'World', 'This', 'Is', 'a', 'List']);
const [first, second, ...theRest] = list;
console.log(first);
> "Hello"
console.log(second);
> "World"
console.log(theRest);
> ["This", "Is", "a", "List"]
Upvotes: 2