Search code examples
javascriptobjectjavascript-objectsdestructuring

Destructure same variables from multiple objects


I have 3 objects

 var first = {name:'ab', age:'12',year:'2010',color:'red'};
var second = {name:'ax', age:'14',year:'2011',mood:'sour'};
var third = {name:'ay', age:'15',year:'2012',dessert:'cake'};

I need to access the items within first, second and third, which I presently do via destructuring.

let {name, age, year, color} = a;
//perform some action here
let {name, age, year, mood} = b;
//perform some action here
let {name, age, year, dessert} = c;
//perform some action here.

Note: For this eg. I am only showing few items inside each object, in the real world case I have around 20+ with 15 of them repeating in all of them.

Since I have name, age and year repeating every time, is there a way to optimize the code that I can declare these 3 variables elsewhere and just mention that while destructuring.

For eg:

let commonVars = {name, age, year}
let {...commonvars, color} = a;
let {...commonvars, mood} = b;
let {...commonvars, dessert} = c;

Because I seem to keep repeating this over and over.


Solution

  • You can add updateCommonVars function and have commonVars object which holds all common values. Use it as updateCommonVars(first); to copy values to commonVars object. And use commonVars.name etc.

    let updateCommonVars = (obj) => {
      for (prop in commonVars)
        commonVars[prop] = obj[prop];
    }
    
    var first = {name:'ab', age:'12',year:'2010',color:'red'};
    var second = {name:'ax', age:'14',year:'2011',mood:'sour'};
    var third = {name:'ay', age:'15',year:'2012',dessert:'cake'};
    
    let commonVars = {name:null, age:null, year:null};
    
    updateCommonVars(first);
    let { color } = first;
    console.log(commonVars.name);
    
    updateCommonVars(second);
    let { mood } = second;
    console.log(commonVars.name);