1

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?

2
  • 1
    Does let { id, name } = user.toJS(); work? Commented Sep 16, 2016 at 6:39
  • 1
    Don't use .toJS() like that, it is a rather expensive operation to just get a few values. Commented Sep 16, 2016 at 16:33

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.