0

currently I am using two ways to copy an object: the first one is

let obj2 = {...obj}

the second one is

let obj2 = Object.assign({}, obj)

which one should be the recommended one? thanks

Benjamin Li
  • 1,687
  • 7
  • 19
  • 30
  • How do you spread an object? I'd say the second one ? – adeneo Oct 18 '16 at 23:31
  • Perhaps this is already answered here http://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object – megalucio Oct 18 '16 at 23:31
  • 1
    ES2015 suggests the Object.assign() in order to execute such operation. Learn more https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – Victor Hugo Montes Oct 18 '16 at 23:35
  • @adeneo, this is my .babellrc { "presets": ["es2015"], "plugins": ["transform-object-rest-spread"] } – Benjamin Li Oct 18 '16 at 23:45

1 Answers1

0

Assuming you're compiling with Babel, they are basically the same:

var a = {...b};

Compiles into:

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var a = _extends({}, b);

I suppose the object spread syntax is slightly better since it will still work if your environment doesn't support Object.assign.

SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • 1
    Babel's "try it out" page: https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&experimental=true&loose=false&spec=false&code=var%20a%20%3D%20%7B...b%7D%3B – SimpleJ Oct 18 '16 at 23:45