Object Destructuring

10 0 0
                                        

Destructuring works in objects too. The first difference is that arrays used brackets while objects used braces. And second difference is that arrays can name any variable they want while objects are required to have the same name as their keys. If you want to rename it, use a colon beside the variable followed by the name.

let object = {

    key1: value1,

    key2: value2,

    key3: value3

   key4: value4

};

syntax 1:

let {key1, key2, key3} = object;

    - key1 = value1, key2 = value2, key3 = value3

   - other keys which are not included will be ignored

syntax 2: (using varargs)

let {key1, ...z} = object;

    - key1 = value1

   - varargs z = [Object object]. There was an error but it still displayed the result Object object. Since it was an object, of course the varargs will return an object.

syntax 3: (using default values)

let {key1, key2, key3, key4, key5 = 100} = object;

    - you can set a default value for keys that are not yet defined in the object.

Note: There was another syntax where you can rename the keys but I did not included since I could not comprehend if it is useful or not. Anyway, just use a colon in the declared keys like key1: x. Then, this way you can use the x as the new name for key1.


===================

let book1 = {

    title: "Reincarnated as a Slime",

    author: "Rimuru"

}

function displayTheBook1(){

    let {author, title} = book1

    document.writeln('title: ${title}');

   document.writeln('author: ${author}');

}

==================

HTML

displayTheBook1()

Result:

title: Reincarnated as a Slime author: Rimuru

Note: In objects, you can interchanged the order but would result to the same value per key.


=====================

let book1 = {

    title: "Reincarnated as a Slime",

    author: "Rimuru",

    otherInfo: {

       published: 2021,

       character_type: "Demon Slime"

    }

};

function displayTheBook1(){

    let {

        title,

        author,

       otherInfo: {

           published,

           character_type

       }

    } = book1;

    document.writeln(title);

    document.writeln(author);

    document.writeln(published);

    document.writeln(character_type);

}

=====================

HTML:

displayTheBook1()

Result:

Reincarnated as a Slime Rimuru 2021 Demon Slime


Note: Take note of how the destructuring and the object declaration is arrange in the above example. It has similar pattern. You can even target nested objects. Also, these kind of destructuring is also applicable in arrays and other data structures.


Javascript ProgrammingWhere stories live. Discover now