Is it possible to destructure onto an existing obj

2019-01-02 18:03发布

For example if I have two objects:

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

and

var oof = {}

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?

perhaps something like:

oof{x,y} = foo

14条回答
萌妹纸的霸气范
2楼-- · 2019-01-02 18:55

While ugly and a bit repetitive, you can do

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

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;

or

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

though.

查看更多
忆尘夕之涩
3楼-- · 2019-01-02 18:55

BabelJS plugin

If you are using BabelJS you can now activate my plugin babel-plugin-transform-object-from-destructuring (see npm package for installation and usage).

I had the same issue described in this thread and for me it was very exhausting when you create an object from a destructuring expression, especially when you have to rename, add or remove a property. With this plugin maintaining such scenarios gets much more easier for you.

Object example

let myObject = {
  test1: "stringTest1",
  test2: "stringTest2",
  test3: "stringTest3"
};
let { test1, test3 } = myObject,
  myTest = { test1, test3 };

can be written as:

let myTest = { test1, test3 } = myObject;

Array example

let myArray = ["stringTest1", "stringTest2", "stringTest3"];
let [ test1, , test3 ] = myArray,
  myTest = [ test1, test3 ];

can be written as:

let myTest = [ test1, , test3 ] = myArray;
查看更多
登录 后发表回答