Object literal

var obj = {
    name: 'Shane',
    age: 31,
    employed: true,
    salaries: [11111, 222222],
    sayName: function() {
        return name;
    }
};

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);

Seal, Freeze & preventExtensions

  • Normal object - CREATE/READ/UPDATE/DELETE
  • Object.freeze() - READ
  • Object.seal() - READ/UPDATE
  • Object.preventExtensions() - READ/UPDATE/DELETE

Object.seal()

Objects can be read and updated, but not deleted.

  • Cannot add new properties
  • Cannot delete existing properties
  • Marks all existing properties as non-configurable. Unlike Object.freeze() it’s writable
Object.isSealed(obj)

Object.freeze()

Objects are only readable. This does everything that Object.seal() does plus prevents modifying any existing properties.

// Boolean
Object.isFrozen(obj)

Deep freeze

Object.freeze() will not deep freeze, eg add to nested bits of objects

user.address.city = 'London';
log(user.address.city); // Other
function deepFreeze(object) {
  Object.getOwnPropertyNames(object).forEach(name => {
    var prop = object[name];
    
    if (prop && typeof prop === 'object')
      deepFreeze(prop);
  });
  
  return Object.freeze(object);
}

Object.preventExtensions()

Also inherits behaviour from Object.seal() with the only difference being that objects can be deleted.

const object1 = {};
Object.preventExtensions(object1);
object1.name = 'sgae';
// {}
console.log(object1);

Refs