Monday, 20 January 2020

Javascript : Destructuring


With the help of destructuring we can unpack values from Arrays and objects into variables directly.
It's vary common to initialize a variable form object property or array like:

let test1=arr[0], test2=arr[1] or 
let name=customer.name,etc.
Below examples will be helpful to understand Destructing in Javascript.

//array destructuring 

let arr = [90300930200];
[jk= arr;
console.log(j + " " + k);

// ... (rest operator)

[lm...p= arr;
console.log(l + " " + m);
console.log(typeof p + " " + p);

//************ object destructring ************:
//Example 1:
let { ab } = { a: 10b: 30c: 90 };
console.log(a + " " + b);

//Exaple 2: object function destrucring
let obj = {
    write: function () {
        console.log("hello");
    }
}
let { write } = obj
write();

//Destructuring with function argument
// Normally we work with object like below
let obj2 = {
    firstname: "nirnajan"
}

function WriteToConsole(val) {
    console.log(val);
}
WriteToConsole(obj2.firstname);//rsult:niranjan


//Destructuring : instead of passing object we can extract param directly
function WriteToConsole2({ firstname }) {
    console.log(firstname);
}
WriteToConsole2(obj2);


//Some complex (nested object)destructuring examples
let customer = {

    firstName: "abc",
    lastName: "bcd",
    Order: [{
        orderDate: '12/12/2020',
        orderId: 1
    }],

}

// To destructing from array within object
let { firstNameOrder: [{ orderId }] } = customer;
console.log(firstName + "****" + orderId);


//another example:
var user = {
    id: 42,
    displayName: 'jdoe',
    fullName: {
        firstName: 'John',
        lastName: 'Doe'
    }
};
let { displayNamefullName: { firstNamename } } = user;

//here firstName:name means renaming 'firstName to name' 
// i.e displayName=user.dispalyName
// name=fullName.firstName
console.log(displayNamename);

No comments:

Post a Comment

JQuery : Quick Review

JQuery Selectors :selectors allows us to find a html elements so, we can manipulate it's attributes programmatically.  Id Sele...