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

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

    I came up with this method:

    exports.pick = function pick(src, props, dest={}) {
        return Object.keys(props).reduce((d,p) => {
            if(typeof props[p] === 'string') {
                d[props[p]] = src[p];
            } else if(props[p]) {
                d[p] = src[p];
            }
            return d;
        },dest);
    };
    

    Which you can use like this:

    let cbEvents = util.pick(this.props.events, {onFocus:1,onBlur:1,onCheck:'onChange'});
    let wrapEvents = util.pick(this.props.events, {onMouseEnter:1,onMouseLeave:1});
    

    i.e., you can pick which properties you want out and put them into a new object. Unlike _.pick you can also rename them at the same time.

    If you want to copy the props onto an existing object, just set the dest arg.

提交回复
热议问题