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

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

    This is the most readable and shortest solution I could come up with:

    let props = { 
      isValidDate: 'yes',
      badProp: 'no!',
    };
    
    let { isValidDate } = props;
    let newProps = { isValidDate };
    
    console.log(newProps);
    

    It will output { isValidDate: 'yes' }

    It would be nice to some day be able to say something like let newProps = ({ isValidDate } = props) but unfortunately it is not something ES6 supports.

提交回复
热议问题