是否可以在解构另一个对象时分配一个对象(在解构中使用默认值)

Is it possible to assign an object while destructuring another (WHILE using defaults in destructuring)

我的最终目标是能够在分配默认值(如果它们不存在)的同时使用 spread operator from an object that is destructured 分配新对象。

看起来这不可能是我想要的。这是我的期望和尝试:

//Expected beginning object
const a1 = {
  key1: "test1",
  key2: "test2",
};

//Expected end result
const b1 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "nestedVal1",
  },
};

//Expected beginning object
const a2 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  }
}

//Expected end result
const b2 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  },
};

代码段 1:不分配 default 值。

const a = {
  key1: "test1",
  key2: "test2",
}

const {...b} = {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
  key4 = 'someDefault'
} = a

console.log(b); // does not have key3, or key4
console.log(key4); //this exists as a const, key3 does not

代码段 2:功能正常,但如果需要多层嵌套,可能会出现问题。

const a = {
  key1: "test1",
  key2: "test2",
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = a

const key3 = a.key3 || {}; // is it possible to include this in the destructuring? Specifically in the destructuring which defines the default.

const b = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(b);

代码段 2(显示嵌套对象未被覆盖)

const a = {
  key1: "test1",
  key2: "test2",
  key3: {
    someOtherKey: "itWorks",
  }
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = a

const key3 = a.key3 || {};

const b2 = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(b2);

您的困惑源于解构语法与对象声明语法的相似性。

这是对象声明:

const a = {
  key1: "test1",
  key2: "test2",
}

这是解构

const { key1, key2 } = a

console.log(key1)  // => test1
console.log(key2)  // => test2

接下来,你需要记住赋值运算符=在JavaScript中是右结合的。所以像

let a = b = 1

表示将值1赋给b,再赋给a

接下来,如果您将所有值分散到一个 var 中,那么您实际上是在使用奇特的 ES6 语法进行简单的赋值。所以:

const {...b} = a
// is same as
const b = a

结合以上3个效果,得到的实际上是一个多重赋值:

const {...b} = a  
const {key1, key2} = a

多重赋值可能会造成混淆,有 linting 规则可以防止此类问题:https://eslint.org/docs/rules/no-multi-assign

所以你的问题的答案很简单,不! :)

这样做至少需要 2 行 - 一行用于在解构时收集具有默认值的道具,另一行用于使用这些道具创建下一个对象。