Search code examples
javascriptecmascript-6object-literal

JavaScript object literals and ES6 - syntatic sugar to deconstruct large object into smaller ones?


What I'm wondering is; is there a simpler syntatic shortcut to what I'm trying to do here.

I have one large JSON object during a loop, like so:

let line = {
    first_name: ...,
    last_name: ...,
    title: ...,
    email: ...,
    facebook_account: ...,
    linkedin_account: ...,
    twitter_account: ...,
    instagram_account: ...,
    snapchat_account: ...
};

I then break this payload down into smaller objects:

let profile = {
    first_name: line.first_name,
    last_name: line.last_name,
    title: line.title,
    email: line.email
};

let social = {
    facebook_account: line.facebook_account,
    linkedin_account: line.linkedin_account,
    twitter_account: line.twitter_account,
    instagram_account: line.instagram_account,
    snapchat_account: line.snapchat_account 
};

Does ES6 afford me a way to cut the repetition of each property i.e. first_name, facebook_account, etc.? The property names are not necessarily obvious in regards to how they get broken down - it's based on our data model.

This is a lot of manual work w/ a lot of repetition. I wonder if I'm missing some piece of ES6 magic, or something, that'd pretty this up. I'm not really looking for a super clever recursive loop with a machine learning algorithm...just shorter syntax, if possible. :)


Solution

  • You can use object destructoring:

    let {variables} = obj

    and individual variable assignment:

    let obj2 = { variables }

    Variables can be multiple and separated by commas.

    When destructoring: let {name, date, whatever} = obj;

    and when assigning: let obj2 = { name, date, whatever }

    let line = {
        first_name: "Zak",
        last_name: "Frisch",
        title: "my Title",
        email: "myemail@whatever",
        facebook_account: "fb",
        linkedin_account: "li",
        twitter_account: "tweet",
        instagram_account: "ia",
        snapchat_account: "sc"
    };
    
    let {first_name, last_name, title, email, facebook_account, linkedin_account, twitter_account, instagram_account, snapchat_account} = line;
    
    let profile = {
        first_name,
        last_name,
        title,
        email
    };
    
    let social = {
        facebook_account,
        linkedin_account,
        twitter_account,
        instagram_account,
        snapchat_account
    };
    console.log(profile, social);