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

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

    You can just use restructuring for that like this:

    const foo = {x:"a", y:"b"};
    const {...oof} = foo; // {x:"a", y:"b"} 
    

    Or merge both objects if oof has values:

    const foo = {x:"a", y:"b"};
    let oof = {z:"c"}
    oof = Object.assign({}, oof, foo)
    

提交回复
热议问题