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

T N*_*yen 4 javascript ecmascript-6

所以我试图找出是否有任何简单的ES6语法可以执行以下操作:

如果我有一个对象

const config = { foo: null, bar: null }
Run Code Online (Sandbox Code Playgroud)

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

const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" }
Run Code Online (Sandbox Code Playgroud)

我想做类似以下的事情,但是没用

{ hello:config.foo, world:config.bar } = source
Run Code Online (Sandbox Code Playgroud)

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

{ hello:foo, world:bar } = source
Run Code Online (Sandbox Code Playgroud)

但这会创建新变量foobar,而我想分配给另一个对象上的现有属性。我只是好奇是否有ES6的简写;我不需要使用传统代码来执行此操作,我知道有十二种方法,而且我已经了解了大多数方法。

chr*_*con 8

您只是()在声明中缺少括号。

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

  • 是的,这是非常违反直觉的语法恕我直言@TNguyen (2认同)