ES6 - 可以从对象解构为另一个对象属性吗?

时间:2018-06-13 18:26:26

标签: javascript ecmascript-6

所以我想弄清楚是否有任何简单的ES6语法来执行以下操作:

如果我有一个对象

const config = { foo: null, bar: null }

我想从另一个对象中分配这些属性的值,例如:

const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" }

我想做类似以下的事情,但它不起作用

{ hello:config.foo, world:config.bar } = source

我知道我可以做一些非常接近的事情:

{ hello:foo, world:bar } = source

但这会创建新变量foobar,而我想分配给另一个对象的现有属性。我只是好奇是否有ES6简写这个;使用传统代码我不需要帮助,我知道有十几种方法,我已经知道了大部分方法。

2 个答案:

答案 0 :(得分:5)

你只是在声明周围丢失括号()

const config = {};
const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" };
({hello: config.foo, world: config.bar} = source);
console.log(config);

答案 1 :(得分:-1)

您需要使用spread运算符来完成此任务:

const newObj = { ...source, hello:config.foo, world:config.bar }

如果您不需要新对象,解决方案就是使用source而不是let声明const

相关问题