0

As the subject, is it OK to use ... in that way to copy properties in an object to another?

Chrome always throws syntax error when I was trying to use it in an object like:

var a = function(){
  return {c: 2};
}

var b = {...a()};
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

1 Answers1

0

In es2018 the spread syntax if applied to an object behaves like object.assign.

var obj1 = { a: 1 }
var obj2 = function() { return {b:2} };
var obj3 = { ...obj1, ..obj2 }

The result would be a new object with combine properties of obj1 and obj2. So obj3 would now be { a:1, b2 }.

ngeksyo
  • 419
  • 3
  • 10
  • 1
    It’s part of ES2018, not ES6. – Sebastian Simon Apr 09 '18 at 10:32
  • @Xufox As done in the question, yes. `For object literals (new in ECMAScript 2018).` [MDN Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). – deEr. Apr 09 '18 at 10:36
  • 1
    You're missing a dot and an invocation at `obj2` – Bergi Apr 09 '18 at 11:19
  • … and a colon at `b2`. – Sebastian Simon Apr 09 '18 at 11:23
  • My chrome version was 59, and I updated it, with version 65 now the problem is gone, I am not missing anything, now the code is running in chrome console perfectly. THX:), this answer is missing a dot before obj2:( it seems, but this method does look like Object.assign – ShuntaoChen Apr 09 '18 at 11:41