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

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

    Other than Object.assign there is the object spread syntax which is a Stage 2 proposal for ECMAScript.

    var foo = {
      x: "bar",
      y: "baz"
    }
    
    var oof = { z: "z" }
    
    oof =  {...oof, ...foo }
    
    console.log(oof)
    
    /* result 
    {
      "x": "bar",
      "y": "baz",
      "z": "z"
    }
    */
    

    But to use this feature you need to use stage-2 or transform-object-rest-spread plugin for babel. Here is a demo on babel with stage-2

提交回复
热议问题