【问题标题】:Is it possible to assign an object while destructuring another (WHILE using defaults in destructuring)是否可以在解构另一个对象时分配一个对象(同时在解构中使用默认值)
【发布时间】:2018-05-26 19:28:30
【问题描述】:

我的最终目标是能够使用 spread operatordestructured 的对象分配一个新对象,同时分配默认值(如果它们不存在)。

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

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

【问题讨论】:

  • 你已经接近了,你只需要记住在使用扩展运算符时顺序很重要,因为后面的值会覆盖前面的值。试试{ ...a, key3: { nestedKey1: "nestedVal1", ...a.key3, } }
  • @Hamms 我已经更新了我的第二个 sn-p 以修复错误。我相信它会按预期运行。如果对象上已经存在一个值——>不要覆盖它。如果不存在,则使用默认值定义它(包括嵌套对象值而不覆盖其他预先存在的键)

标签: javascript json ecmascript-next


【解决方案1】:

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

这是对象声明:

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 行代码 - 一行用于在解构时收集具有默认值的 props,另一行用于使用这些 props 创建下一个对象。

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2021-09-09
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2020-04-09
    相关资源
    最近更新 更多