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

前端 未结 16 1743
暗喜
暗喜 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: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 };
    

提交回复
热议问题