Partial Object Composing in JavaScript ES6

We all had to deal with dynamic object keys at one point and it is a painful process but thanks to the enhanced Object Initialization Spec in ES6, those days are becoming a bit easier.

The [ ] quotation allows to create an object key from a computed value as shown below:

const target = 'foo';

const targets = {
 [target]: 'bar'
}

/* {foo: 'bar'} */

Amazing but how to use it in a realistic environment? Some of my mobile applications require to load a lot of data. I made it a habit to load data partially throughout the life cycle of the application which means that data is coming in randomly, yet I want that data to be structured and stored in a reducer (redux).

My common pattern is to deep extend an object using the _.merge method of the lodash library which allows me to easily put partially loaded data within the same structure of the reducer.


// initial state const state = { people: {} }; // loaded data const person = { id: 5, ref: 'kyloren', name: 'Kylo Ren', email: 'kylo@starkillerbase.com', } // reducer return return _.merge({}, state, { people: { [person.ref]: person } }); // access the state console.log(getState().people.kyloren); // returns the person object

With this method, I am able to continuously extend partially loaded data without corrupting the state and it can be used not only for reducers but for any operation that require application life cycle operations on objects.