With standard JS objects, one can use destructuring assignment such as:
let obj = {name: 'james', code: '007'}
let {name, code} = obj // creates new variables 'name' and 'code' (with the proper values)
As suggested by some Flux / Redux evangelist, I use immutable.js for my app; can I use destructuring also on immutable List / Map? Of course, one could do:
let obj = immutable.fromJS({name: 'james', code: '007'})
let {name, code} = obj.toJS()
but this seems to have quite inefficient as the objects grow bigger (because the object needs to be deeply jsified first).
Update on 12 Aug 2021 Happily, the creator of Immutable JS resumed to maintaining his lib, and commits are regular now. Hope 4.0. 0 comes soon!
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.
Using ImmutableJS can improve dramatically the performance of your application. And, because the immutable data never changes, you can always expect new data to be passed from the above. To make sure you are correctly comparing the data and not updating the UI when there is no change, you should always use the .
The object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. What's better, object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn't exist.
With immutable List, the destructuring works quite straightforwardly. This is because destructuring of Arrays works on every iterable (Checking whether something is iterable) and is not subjected just to js Arrays.
With Map, the situation is more complicated. Unlike with List, the destructuring of Map-like structures IS subjected just to plain JS objects and nothing more. Currently, it does not seem that ES community considers this a good idea (see https://esdiscuss.org/topic/extensible-destructuring-proposal)
However, there exist babel-plugin that enables this: https://github.com/vacuumlabs/babel-plugin-extensible-destructuring
Having this plugin installed and enabled in .babelrc, you can simply patch immutable Map to have a .@@get
method defined:
// main.js, first file loaded
import {Iterable} from 'immutable';
Iterable.prototype[Symbol.for('get')] = function(value) {return this.get(value); };
and everything works (also nested destructuring, or destructuring with default values)
import {fromJS} from 'immutable';
const map = fromJS({author: {name: {first: "John", last: "Doe"}, birthdate: "10-10-2010"}});
const {author: {name: {first, last}, birthdate}} = map;
Disclaimer: I'm one of the authors of the plugin mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With