【问题标题】:Destructure same variables from multiple objects从多个对象中解构相同的变量
【发布时间】:2020-06-10 10:16:07
【问题描述】:

我有 3 个对象

 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 {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.

注意:例如。我只在每个对象中显示几个项目,在现实世界的情况下,我有大约 20 多个,其中 15 个在所有对象中重复出现。

由于我每次都重复姓名、年龄和年份,有没有办法优化我可以在其他地方声明这 3 个变量并在解构时提及的代码。

例如:

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

因为我似乎一遍又一遍地重复这一点。

【问题讨论】:

  • 为什么不使用函数呢? ({name, age, year}) => { /* whatever */}
  • 不,没有。无论如何,您不能重新使用相同的名称。
  • 为什么不能使用点表示法而不是创建新变量? first.namesecond.name。连这个first/fifteenth 好像都用错了
  • 为什么不使用数组?
  • @VLAZ,这些是多个对象,其中大约 15 个变量重复,而其余变量是唯一的。所以我也不能假设。让我更新问题

标签: javascript object javascript-objects destructuring


【解决方案1】:

您可以添加updateCommonVars 函数并拥有commonVars object,它包含所有常见值。将其用作updateCommonVars(first); 以将values 复制到commonVars 对象。并使用commonVars.name 等。

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

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多