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

前端 未结 16 1553
暗喜
暗喜 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.

    0 讨论(0)
  • 2020-11-22 17:08

    While ugly and a bit repetitive, you can do

    ({x: oof.x, y: oof.y} = foo);
    

    which will read the two values of the foo object, and write them to their respective locations on the oof object.

    Personally I'd still rather read

    oof.x = foo.x;
    oof.y = foo.y;
    

    or

    ['x', 'y'].forEach(prop => oof[prop] = foo[prop]);
    

    though.

    0 讨论(0)
  • 2020-11-22 17:12

    You can use JSON class methods to achieve it as follows

    const foo = {
       x: "bar",
       y: "baz"
    };
    
    const oof = JSON.parse(JSON.stringify(foo, ['x','y']));
    // output -> {x: "bar", y: "baz"}
    

    Pass properties that need to be added to the resulting object as second argument to stringify function in an array format.

    MDN Doc for JSON.stringify

    0 讨论(0)
  • 2020-11-22 17:13

    You can return the destructured object in an arrow function, and use Object.assign() to assign it to a variable.

    const foo = {
      x: "bar",
      y: "baz"
    }
    
    const oof = Object.assign({}, () => ({ x, y } = foo));
    
    0 讨论(0)
提交回复
热议问题