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

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

    It's totally possible. Just not in one statement.

    var foo = {
        x: "bar",
        y: "baz"
    };
    var oof = {};
    ({x: oof.x, y: oof.y} = foo); // {x: "bar", y: "baz"}
    

    (Do note the parenthesis around the statement.) But keep in mind legibility is more important than code-golfing :).

    Source: http://exploringjs.com/es6/ch_destructuring.html#sec_assignment-targets

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

    DRY

    var a = {a1:1, a2: 2, a3: 3};
    var b = {b1:1, b2: 2, b3: 3};
    
    const newVar = (() => ({a1, a2, b1, b2})).bind({...a, ...b});
    const val = newVar();
    console.log({...val});
    // print: Object { a1: 1, a2: 2, b1: 1, b2: 2 }
    

    or

    console.log({...(() => ({a1, a2, b1, b2})).bind({...a, ...b})()});
    
    0 讨论(0)
  • 2020-11-22 17:00

    This works in chrome 53.0.2785.89

    let foo = {
      x: "bar",
      y: "baz"
    };
    
    let oof = {x, y} = foo;
    
    console.log(`oof: ${JSON.stringify(oof)});
    
    //prints
    oof: {
      "x": "bar",
      "y": "baz"
    }
    
    0 讨论(0)
  • 2020-11-22 17:00

    It's not a beautiful way, nor I recommend it, but it's possible this way, just for knowledge.

    const myObject = {
      name: 'foo',
      surname: 'bar',
      year: 2018
    };
    
    const newObject = ['name', 'surname'].reduce(
      (prev, curr) => (prev[curr] = myObject[curr], prev),
      {},
    );
    
    console.log(JSON.stringify(newObject)); // {"name":"foo","surname":"bar"}
    
    0 讨论(0)
  • 2020-11-22 17:04

    Other than Object.assign there is the object spread syntax which is a Stage 2 proposal for ECMAScript.

    var foo = {
      x: "bar",
      y: "baz"
    }
    
    var oof = { z: "z" }
    
    oof =  {...oof, ...foo }
    
    console.log(oof)
    
    /* result 
    {
      "x": "bar",
      "y": "baz",
      "z": "z"
    }
    */
    

    But to use this feature you need to use stage-2 or transform-object-rest-spread plugin for babel. Here is a demo on babel with stage-2

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

    IMO this is the easiest way to accomplish what you're looking for:

    let { prop1, prop2, prop3 } = someObject;
    let data = { prop1, prop2, prop3 };
    
      // data === { prop1: someObject.prop1, ... }
    

    Basically, destructure into variables and then use the initializer shorthand to make a new object. No need for Object.assign

    I think this is the most readable way, anyways. You can hereby select the exact props out of someObject that you want. If you have an existing object you just want to merge the props into, do something like this:

    let { prop1, prop2, prop3 } = someObject;
    let data = Object.assign(otherObject, { prop1, prop2, prop3 });
        // Makes a new copy, or...
    Object.assign(otherObject, { prop1, prop2, prop3 });
        // Merges into otherObject
    

    Another, arguably cleaner, way to write it is:

    let { prop1, prop2, prop3 } = someObject;
    let newObject = { prop1, prop2, prop3 };
    
    // Merges your selected props into otherObject
    Object.assign(otherObject, newObject);
    

    I use this for POST requests a lot where I only need a few pieces of discrete data. But, I agree there should be a one liner for doing this.

    EDIT: P.S. - I recently learned you can use ultra destructuring in the first step to pull nested values out of complex objects! For instance...

    let { prop1, 
          prop2: { somethingDeeper }, 
          prop3: { 
             nested1: {
                nested2
             } 
          } = someObject;
    let data = { prop1, somethingDeeper, nested2 };
    

    Plus, you could use spread operator instead of Object.assign when making a new object:

    const { prop1, prop2, prop3 } = someObject;
    let finalObject = {...otherObject, prop1, prop2, prop3 };
    

    Or...

    const { prop1, prop2, prop3 } = someObject;
    const intermediateObject = { prop1, prop2, prop3 };
    const finalObject = {...otherObject, ...intermediateObject };
    
    0 讨论(0)
提交回复
热议问题