是否可以在现有对象上进行解构?(Javascript ES6) [英] Is it possible to destructure onto an existing object? (Javascript ES6)

查看:23
本文介绍了是否可以在现有对象上进行解构?(Javascript ES6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有两个对象:

For example if I have two objects:

var foo = {
  x: "bar",
  y: "baz"
}

var oof = {}

我想将 x 和 y 值从 foo 转移到 oof.有没有办法使用 es6 解构语法来做到这一点?

and I wanted to transfer the x and y values from foo to oof. Is there a way to do that using the es6 destructuring syntax?

可能是这样的:

oof{x,y} = foo

推荐答案

虽然丑陋且有点重复,但你可以做到

While ugly and a bit repetitive, you can do

({x: oof.x, y: oof.y} = foo);

它将读取foo 对象的两个值,并将它们写入oof 对象上的各自位置.

which will read the two values of the foo object, and write them to their respective locations on the oof object.

我个人还是比较喜欢阅读

Personally I'd still rather read

oof.x = foo.x;
oof.y = foo.y;

['x', 'y'].forEach(prop => oof[prop] = foo[prop]);

虽然.

这篇关于是否可以在现有对象上进行解构?(Javascript ES6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆