Javascript Essentials ES6

Object to String Array of the object keys

const strArrKeys = Object.keys(jsObjectVariable);

Object to Array with Key Value pairs

let theobj = {
  key1: "value1",
  key2: "value2"
}

Object.entries(theobj).forEach(eachKeyVal => {
  console.log("Key is " + eachKeyVal[0] + " and value is " + eachKeyVal[1])
});

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 =>  jsObjectVariable[k] ); // Retruns an Array of values 
console.log(strArr);

const strArr2 = Object.keys(jsObjectVariable) // Returns ARRAY of the keys
                 .map(k => {  return jsObjectVariable[k] }
                 ); // Retruns an Array of values 
console.log(strArr2);

jsARRVariable  = [(one => 1),(two => 2)];

const strArr3 = jsARRVariable.map((k,v) => {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) => 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:

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

Leave a Reply

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


CAPTCHA Image
Reload Image