Javascript Essentials ES6

Object to String Array of the object keys

 const strArrKeys = Object.keys(jsObjectVariable); 


Object to Array with Key Value pairs

<br />let theobj = { key1: "value1", key2: "value2" }<br />Object.entries(theobj).forEach(eachKeyVal =&gt;<br />   { console.log("Key is " + eachKeyVal[0] + " and value is " + eachKeyVal[1]) }); <br />

Array from object values

 jsObjectVariable = { one : 1, two: 2, three: { temp1: "t1", temp2: "t2" } } const strArr = Object.keys(jsObjectVariable) // Returns ARRAY of the keys .map(k =&amp;amp;amp;amp;amp;gt; jsObjectVariable[k] ); // Retruns an Array of values console.log(strArr); const strArr2 = Object.keys(jsObjectVariable) // Returns ARRAY of the keys .map(k =&amp;amp;amp;amp;amp;gt; { return jsObjectVariable[k] } ); // Retruns an Array of values console.log(strArr2); jsARRVariable = [(one =&amp;gt; 1),(two =&amp;gt; 2)]; const strArr3 = jsARRVariable.map((k,v) =&amp;gt; {return v;} ); // Returns array of values console.log(strArr3); 

Make a copy of the object.

cont newObject = {...oldObject};

Make a copy of the array.

cont newArray = [...oldArray];

Add values to an Array immutably.
Dont use push use concat, it will make a copy of the array.
Add an integer called counter to an array called results:

cont newObject = {
    ...oldObject,
    results: oldObject.results.concat(oldObject.counter)
};

Delete values from an Array immutably.

const idToDelete = 4;
const newArray = [...oldArray];
newArray.splice(idToDelete,1);

OR

newArray = oldArray.filter((result,index) =&amp;amp;amp;amp;amp;gt; index !== idToDelete);

You can also create dynamic object keys (Object Names based on variables) and use them

var example = {one : 'something', two: 'somethingElse'};
var test = {
    [example.one]: true,
    [example.two]: function () { console.log('This is SomethingElse function Result');},
};

console.log(test.something);
test.somethingElse();

IN ES5 we used to:

var key = 'dynamicKey';
var o = {};
o[key] = 'value';

But in ES6, when creating an object literal, you can do this:

ccc
var key = 'dynamicKey';
var o = { [key]: 'value' };
[/sourcecode]

Shorthand ( Destruct Assignment Shorthand)

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;

//Shorthand is:
import { observable, action, runInAction } from 'mobx';
const { store, form } = this.props;
//Or Even Rename the variable
const { store, form:myvariablenameforform } = this.props;

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image