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

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

    You can use JSON class methods to achieve it as follows

    const foo = {
       x: "bar",
       y: "baz"
    };
    
    const oof = JSON.parse(JSON.stringify(foo, ['x','y']));
    // output -> {x: "bar", y: "baz"}
    

    Pass properties that need to be added to the resulting object as second argument to stringify function in an array format.

    MDN Doc for JSON.stringify

提交回复
热议问题