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

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

    This is kind of cheating, but you can do something like this...

    const originalObject = {
      hello: 'nurse',
      meaningOfLife: 42,
      your: 'mom',
    };
    
    const partialObject = (({ hello, your }) => {
      return { hello, your };
    })(originalObject);
    
    console.log(partialObject); // ​​​​​{ hello: 'nurse', your: 'mom' }​​​​​
    

    In practice, I think you'd rarely want to use that though. The following is MUCH more clear... but not nearly as fun.

    const partialObject = {
      hello: originalObject.hello,
      your: originalObject.your,
    };
    

    Another completely different route, which includes mucking with the prototype (careful now...):

    if (!Object.prototype.pluck) {
      Object.prototype.pluck = function(...props) {
        return props.reduce((destObj, prop) => {
          destObj[prop] = this[prop];
    
          return destObj;
        }, {});
      }
    }
    
    const originalObject = {
      hello: 'nurse',
      meaningOfLife: 42,
      your: 'mom',
    };
    
    const partialObject2 = originalObject.pluck('hello', 'your');
    
    console.log(partialObject2); // { hello: 'nurse', your: 'mom' }
    

提交回复
热议问题