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

前端 未结 16 1569
暗喜
暗喜 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 16:58

    It's totally possible. Just not in one statement.

    var foo = {
        x: "bar",
        y: "baz"
    };
    var oof = {};
    ({x: oof.x, y: oof.y} = foo); // {x: "bar", y: "baz"}
    

    (Do note the parenthesis around the statement.) But keep in mind legibility is more important than code-golfing :).

    Source: http://exploringjs.com/es6/ch_destructuring.html#sec_assignment-targets

提交回复
热议问题