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

标签 javascript json ecmascript-next

我的最终目标是能够使用 spread operator 分配一个新对象来自 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

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

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

关于javascript - 是否可以在解构另一个对象时分配一个对象(在解构中使用默认值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47784020/

相关文章:

javascript - 中间变量——性能成本是多少?

AngularJS - $httpBackend 无法读取嵌套的 JSON 属性

javascript - 通过索引检索 JSON 对象的属性

c# - 如何使用 JSON.NET 保存具有四个空格缩进的 JSON 文件?

javascript - 实现用于链接类方法的 JS 装饰器

javascript - 使用 javascript 操作伪元素

javascript - 整合angular和joint js

javascript - ESNext : What's the purpose of the `async` keyword?

javascript - TypeError : Object. 条目不是函数

javascript - jQuery 中的正则表达式