adimetrius
adimetrius

Reputation: 101

How to do REAL object assignment in JS (shallow copy)

In JS, I need to make a shallow copy of an object. It seems that Object.assign() is the only option. Is this true, or are there other ways? I would prefer a syntactic method that would do it inside an assignment (that would be an expression rather than a statement). Something to replace (*1*):

var a = { x:1978 }; b = a; c = { x:2001 }; [ b ] = [ (*1*) ]
/* I need (a === b) && (b.x === c.x) to hold here */

Upvotes: 0

Views: 40

Answers (1)

user10987633
user10987633

Reputation:

There's always spread syntax, which can be used for objects and other things:

b = {...b, ...c}

(as an alternative to Object.assign())

Upvotes: 1

Related Questions