Is it possible to destructure onto an existing object? (Javascript ES6)

前端 未结 16 1739
暗喜
暗喜 2020-11-22 16:24

For example if I have two objects:

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

and

var oof = {}

and I want

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 17:08

    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.

提交回复
热议问题