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

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

提交回复
热议问题