Jump to Categories

Objects

Make an object

const whatever = {};
const whatever = new Object();

Get the object keys

const obj = {a: 1, b: 2, c: 3};
// ["a", "b", "c"]
console.log(Object.keys(obj));

Loop through an object

Object.keys(myObj).forEach(key => {
    // the name of the current key.
    console.log(key);
    // the value of the current key.
    console.log(myObj[key]);
});

Convert object into a JSON string

// returns "{"physics":98,"maths":95,"chemistry":91}"
JSON.stringify(marks);
// Get object from string
JSON.parse('{"physics":98,"maths":95,"chemistry":91}');

Object destructuring

const o = {name: 'Shane', age: 42};
const {name, age} = o;

// Shane
console.log(name);
// 42
console.log(age);

Assigning to new variable names

const o = {name: 'Shane', age: 42};
const {name:name2, age:age2} = o;

// Shane
console.log(name2);
// 42
console.log(age2);

Refs