JavaScript Object Basic to Advance

Index

  1. What is Object ?
  2. How to create object ?
  3. Access object keys
  4. Reference Type
  5. Object.assign, JSON.parse and JSON.stringify
  6. Let and Const
  7. Delete Keys
  8. DefineProperty
  9. DefineProperties
  10. Key note for DefineProperty
  11. Freeze
  12. Seal
  13. Create Object from Array

1. What is Object

Object is a non-primitive data type in JavaScript. It is like any other variable, the only difference is that an object holds multiple values in terms of properties and methods. Properties can hold values of primitive data types and methods are functions. tutorialsteacher

In simple words, we can say JavaScript object are collections of key-value pairs. Where each key is a unique and each key can store different type of value like structure in C .

Technically we can say JavaScript object is implementation of hashing .In hashing retrieve value required O(1) time complexity and JavaScript object also need O(1) time complexity for retrieve any key.

Syntax

{
      key_1: Value,
      key_2: Value,
      ...
      key_n: Value
}

Notes:

a. Object always overwrite the duplicate key.

b. Object alway add key, if its not present already.

c. In object we can't define the order of keys

2. How to create Object

obj = {
   name: "Jhon",
   age:  25,
   height: 5.7 
};
console.log(obj)

Above example is very simple way to crate object. Here "obj" is name of the object and "name, age, height" are the key of object "obj". If we define same key multiple time then it will consider last value.

obj = {
   name: "Jhon",
   name: "Joy",
   age:  25,
   height: 5.7 
};
console.log(obj);// {name: "Joy", age: 25, height: 5.7}

3. Access object values

Get value from object

console.log(obj.name) // Joy
console.log(obj['age']) // 25

First one known as "dot" notation and second one known as "bracket" notation

Get all keys of a object

all_keys = Object.keys(obj);
console.log(all_keys); // ["name", "age", "height"]

We can iterate over object to get its all value

for(let key in obj){
    console.log(key, '-> ', obj[key])
}
//Output will be
//name ->  Joy
//age ->  25
//height ->  5.7

Add new key and update existing key

obj['country']= "India";
console.log(obj);  // {name: "Joy", age: 25, height: 5.7, country: "India"}

It will check "country" key is present or not if present, then update the value else, add this key with its given value

obj.age = 27;
console.log(obj) // {name: "Joy", age: 27, height: 5.7, country: "India"}

4. Reference Type

Objects are always "reference type" like pointer in C. Means if you assign obj to obj1

obj1 = obj;

then whatever changes we make either obj and obj1, will be reflect in both obj1 and obj

obj1 = obj
console.log(obj1)//{name: "Joy", age: 27, height: 5.7, country: "India"}
obj1.name = "Jony";
obj.height = 6.0;
console.log(obj); //{name: "Jony", age: 25, height: 6, country: "India"}
console.log(obj1); // {name: "Jony", age: 25, height: 6, country: "India"}

5. Object.assign, JSON.parse and JSON.stringify

Object.assign one of the most powerful method. Its used for different purpose

a. Merge two or multiple objects into one object

b. Create an object from another object

c. Assign one object to another object without reference

obj = { a: 1, b: 2, c: 3};
obj_1 = {d: 4, e: 5};
obj_2 = {d: 44, f: 6, b: 22};
obj=Object.assign(obj, obj_1, obj_2);
console.log(obj); //{a: 1, b: 22, c: 3, d: 44, e: 5, f: 6}

Here we merge obj_1, obj_2 into obj. During merging if its found same key in multiple object then it will consider last updated value else add keys.

obj = {a: 1, b: 2, c: 3};
new_obj = Object.assign({}, obj);
console.log(new_obj); //{a: 1, b: 2, c: 3}

Here we create new_obj from obj

obj = {a: 1, b: 2, c: 3};
obj_1 = obj;

This type of assignment maintain the reference, means changes in obj_1 also reflect to the obj. But we want to assign one object to another without reference

obj = {a: 1, b: 2, c: 3};
obj_1 = Object.assign({}, obj);
obj_1.a = 10;
console.log(obj); //{a: 1, b: 2, c: 3}
console.log(obj_1); //{a: 10, b: 2, c: 3}

This assignment also have an issue.

obj = {a: 1, b: 2, c: 3, d: {e: 10, f: 20}};
obj_1 = Object.assign({}, obj);
obj_1.d.e = 100;
obj_1.a = 20
console.log(obj);  //{a: 1, b: 2, c: 3, d: {e: 100, f: 20}}
console.log(obj_1); // {a: 20, b: 2, c: 3, d: {e: 100, f: 20}}

Here 'd' is nested object and changes of 'a' not reflect in obj but changes of 'e' reflect in both objects. Because Object.assign() not able copy nested object completely, for nested object it work same as normal assignment.

JSON.stringify method used to convert an object to string.

obj = {a: 1, b: 2, c: 3, d: {e: 10, f: 20}};
obj_str = JSON.stringify(obj);
console.log(obj_str); // "{"a":1,"b":2,"c":3,"d":{"e":10,"f":20}}"

JSON.parse method use for convert a string to Object

new_obj = JSON.parse(obj_str);
console.log(new_obj); //  {a: 1, b: 2, c: 3, d: {e: 10, f: 20}}

In case of object.assign() we found that it will not able to break the reference of nested object property. We can achieve this solution by JSON.parse and JSON.stringify.

obj = {a: 1, b: 2, c: 3, d: {e: 10, f: 20}};
new_obj = JSON.parse(JSON.stringify(obj));
new_obj.d.e = 100;
console.log(obj); // {a: 1, b: 2, c: 3, d: {e: 10, f: 20}}
console.log(new_obj); // {a: 1, b: 2, c: 3, d: {e: 100, f: 20}}

6. Let and Const

if we declare a variable using let then we can change its value as much as we want.

let obj = {a: 1, b: 2, c: 3};
obj = {name: 'Joy', age: 25};
console.log(obj); //{name: 'Joy', age: 25}

But if we define a variable using const then we can't change its value, same rules also applicable for object also

const obj = {a: 1, b: 2, c: 3};
obj = {name: 'Joy', age: 25}; // Uncaught TypeError: Assignment to constant variable.

But we can add new key, we can change the value of any key

const obj = {a: 1, b: 2, c: 3};
obj.a = 23;
obj['d'] = 4;
console.log(obj); // {a: 23, b: 2, c: 3, d: 4}

7. Delete Keys

obj = {a: 1, b: 2, c: 3};
delete obj.a
console.log(obj); //{b:2, c: 3}
delete obj['b'];
console.log(obj); // {c: 3}

8. DefineProperty

Every key in an object define with some configuration

  1. Key is writeable or not
  2. Key is deletable or not
  3. Key is iteratable or not
  4. and so on.

Object.defineProperty() method allow to configure a new key or existing key of an object.

Syntax

Object.defineProperty(object_name, key_name, {configuration_filed: value})

Now create one object

let student = {
    name: "Joy",
    age: 25,
    section: 'A',
    student_id: 121402,
    degree_type: "Master",
    batch_year: "2014-2018"
};

Getter and Setter

//define setter
Object.defineProperty(student, 'set_data', {
    set: function (values){
        values.age? student.age = values.age: '';
        values.section? student.section = values.section : '';
    }
});

//define getter
Object.defineProperty(student, 'get_data', {
    get: function (){
        return student;
    }
});
student.set_data = {age: 27, section: 'B'};
console.log(student.get_data); // {age: 27,batch_year: "2014-2018",degree_type: "Master",name: "Joy",section: "B",student_id: 121402}

writable

We want "batch_year" key can't be change, it means make batch_year like act as a constant.

Object.defineProperty(student, 'batch_year', {
    writable: false
});
student.batch_year = '2019-2023';
console.log(student.batch_year); // "2014-2018"

Now "batch_year" we cant edit, but we can delete it. Writable only prevent the edit not delete.

delete student['batch_year'];
console.log(student); //{age: 27, degree_type: "Master", name: "Joy", section: "B", student_id: 121402}

Configurable

Now we want that degree_type can be change but can not be delete.

Object.defineProperty(student, 'degree_type', {
    configurable: false
});
student.degree_type = 'UG';
console.log(student.degree_type); // 'UG'
delete student.degree_type;
console.log(student); // {age: 27, degree_type: "UG", name: "Joy", section: "B", student_id: 121402}

enumerable

student_id generally should neither be delete nor edit and also should be hide from outside.

Object.defineProperty(student, 'student_id', {
    writable: false,
    configurable: false,
    enumerable: false
});
student.student_id = 123;
console.log(student.student_id); // 121402, so not editable
delete student.student_id;
console.log(student.student_id); // not deletable
const keys = Object.keys(student);
console.log(keys); //["age", "degree_type", "name", "section"]
for(let key in student){
  console.log(key);
}
//Output of the for loop will be
//age
//degree_type
//name
//section

We can see that student_id become not iterate able, it is hide from outside world.

9. DefineProperties

Object.defineProperties same as Object.defineProperty, only difference is defineProperties allow multiple key allow and defineProperty only allow one key at a time.

Object.defineProperties(obj, {
    a: {writable: false},
    b: {configurable: false},
    c: {enumerable: false}
});

10. Key note for DefineProperty and defineProperties

  1. When we define key simply, then keys can be edit, delete and iterate, configurable and enumerable are true.
    obj = {a: 1, b: 2, c: 3};
    obj.a = 20;
    console.log(obj.a); // 20
    Object.keys(obj); //['a', 'b', 'c']
    delete obj.a;
    console.log(obj); //  {b: 2, c: 3}
    
  2. When we define new key using defineProperty, then default value for writable, configurable and enumerable are false.
obj = {a: 1, b: 2, c: 3};
Object.defineProperty(obj, 'd', {
    value: 20,
    writable: false
});
console.log(obj.d); // 20
obj.d = 100;
console.log(obj.d); // 20
delete obj.d;
console.log(obj.d); // 20
Object.keys(obj); // ["a", "b", "c"]

So, when we define new key using defineProperty we need to specify all the configuration.

obj = {a: 1, b: 2, c: 3};
Object.defineProperty(obj, 'd', {
    value: 20,
    writable: true,
         configurable: true,
         enumerable:  true
});

11. Freeze

Let assume, we want to make one object, which should be act like as constant. Means it will not allow to change keys value, delete keys and it will not allow to add any new keys.

obj = {a: 1, b: 2, c: 3};
Object.freeze(obj)
obj.a = 20;
console.log(obj.a); // 20
delete obj.a;
console.log(obj.a); // 20
obj['d'] = 40;
console.log(obj); // {a: 1, b: 2, c: 3}
console.log(Object.keys(obj)); //["a", "b", "c"]

12. Seal

Now we want to make one object such that it will not allow to delete any key and add any new key. But allow to change existing keys value

obj = {a: 1, b: 2, c: 3};
Object.seal(obj);
obj.a = 40;
console.log(obj.a); // 40
delete obj.a;
console.log(Object.keys(obj)); // ["a", "b", "c"]
obj['d'] = 100;
console.log(Object.keys(obj)); // ["a", "b", "c"]

13. Create Object from Array

arr = [['a', 1], ['b', 2], ['c', 3]];
obj = Object.fromEntries(arr);
console.log(obj); // {a: 1, b: 2, c: 3}

To read more, click here

Abhishek Singh's photo

Very Helpful.

Raghavan alias Saravanan Muthu's photo

Awesome notes that can be kept as a quick reference!