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

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

    No, destructuring does not support member expressions in shorthands but only plain propertynames at the current time. There have been talks about such on esdiscuss, but no proposals will make it into ES6.

    You might be able to use Object.assign however - if you don't need all own properties, you still can do

    var foo = …,
        oof = {};
    {
        let {x, y} = foo;
        Object.assign(oof, {x, y})
    }
    
    0 讨论(0)
  • 2020-11-22 16:46

    You can just use restructuring for that like this:

    const foo = {x:"a", y:"b"};
    const {...oof} = foo; // {x:"a", y:"b"} 
    

    Or merge both objects if oof has values:

    const foo = {x:"a", y:"b"};
    let oof = {z:"c"}
    oof = Object.assign({}, oof, foo)
    
    0 讨论(0)
  • 2020-11-22 16:49

    You can destruct an object assigning directly to another object attribute.

    Working example:

    let user = {};
    [user.name, user.username] = "Stack Overflow".split(' ');
    document.write(`
    1st attr: ${user.name} <br /> 
    2nd attr: ${user.username}`);

    You can work with destructing using variables with the same name of object attribute you want to catch, this way you don't need to do:

    let user = { name: 'Mike' }
    let { name: name } = user;
    

    Use this way:

    let user = { name: 'Mike' }
    let { name } = user;
    

    The same way you can set new values to object structures if they have the same attribute name.

    Look this working example:

    // The object to be destructed
    let options = {
      title: "Menu",
      width: 100,
      height: 200
    };
    
    // Destructing
    let {width: w, height: h, title} = options;
    
    // Feedback
    document.write(title + "<br />");  // Menu
    document.write(w + "<br />");      // 100
    document.write(h);                 // 200

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 16:53

    BabelJS plugin

    If you are using BabelJS you can now activate my plugin babel-plugin-transform-object-from-destructuring (see npm package for installation and usage).

    I had the same issue described in this thread and for me it was very exhausting when you create an object from a destructuring expression, especially when you have to rename, add or remove a property. With this plugin maintaining such scenarios gets much more easier for you.

    Object example

    let myObject = {
      test1: "stringTest1",
      test2: "stringTest2",
      test3: "stringTest3"
    };
    let { test1, test3 } = myObject,
      myTest = { test1, test3 };
    

    can be written as:

    let myTest = { test1, test3 } = myObject;
    

    Array example

    let myArray = ["stringTest1", "stringTest2", "stringTest3"];
    let [ test1, , test3 ] = myArray,
      myTest = [ test1, test3 ];
    

    can be written as:

    let myTest = [ test1, , test3 ] = myArray;
    
    0 讨论(0)
  • 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' }
    
    0 讨论(0)
提交回复
热议问题