1

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.

10
  • Why not use a function? ({name, age, year}) => { /* whatever */} Commented Jun 10, 2020 at 10:17
  • No, there isn't. You can't re-let the same names anyway. Commented Jun 10, 2020 at 10:17
  • Why can't you use dot notation instead of creating new variables? first.name, second.name. Even this first/fifteenth seems to be wrong use Commented Jun 10, 2020 at 10:19
  • 2
    Why are you not using an array? Commented Jun 10, 2020 at 10:21
  • @VLAZ, these are multiple objects where about 15 of the variables repeat, while the rest are unique. So I cannot Assume that either. Let me update the question Commented Jun 10, 2020 at 10:23

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.