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

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

    It's not a beautiful way, nor I recommend it, but it's possible this way, just for knowledge.

    const myObject = {
      name: 'foo',
      surname: 'bar',
      year: 2018
    };
    
    const newObject = ['name', 'surname'].reduce(
      (prev, curr) => (prev[curr] = myObject[curr], prev),
      {},
    );
    
    console.log(JSON.stringify(newObject)); // {"name":"foo","surname":"bar"}
    

提交回复
热议问题