The new destructuring assignment features of ES6 are fairly well known now (live copy on Babel's REPL); in the case of variables that already exist:
let a, b; // Existing variables
let o = {a: "a", b: "b"}; // An object to get values from
// ...
({a, b} = o); // Set them to the props from `o`
console.log(a); // "a"
console.log(b); // "b"
Is there a simple converse in ES6? Setting properties on an existing object based on variables with the same name? (Other than the obvious o.a = a; o.b = b;
)
Note I'm not talking about when creating an object, we could do that with the wonderful new object initializer syntax that lets us not repeat the names unnecessarily:
let a = "a";
let b = "b";
let o = {a, b};
But if I already have an object, can I do some kind of structuring assignment in ES6?
The closest I've come up with is to use
Object.assign
and a temporary object (live copy):It's fairly simple, but it's a function call and a temporary object.
Update: Bergi points out in a comment that there's a strawman proposal (link now dead) for a:=
operator that will do this, and one of their first use cases is indeed the use case that primarily lead me to this question: Constructors:So given that strawman exists, I suspect for now the
assign
is going to be the best I can do in ES6. The old wiki with the strawman is offline, and there's nothing about:=
in the proposals repo.