I'm actually looking for a working answer, similar to destructuring (see )
But I've seen this sample:
[a, b] = [1, 2];
So I was hoping if there's a way to do mass-assigning for multiple object properties, like this:
this.[name, age, is_male] = [ 'John Doe', 22, true ];
To shorten this:
this.name = 'John Doe';
this.age = 22;
this.is_male = true;
Any input would be much appreciated.
I'm actually looking for a working answer, similar to destructuring (see https://developer.mozilla/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
But I've seen this sample:
[a, b] = [1, 2];
So I was hoping if there's a way to do mass-assigning for multiple object properties, like this:
this.[name, age, is_male] = [ 'John Doe', 22, true ];
To shorten this:
this.name = 'John Doe';
this.age = 22;
this.is_male = true;
Any input would be much appreciated.
Share Improve this question asked Oct 12, 2016 at 19:32 Allen LinatocAllen Linatoc 6347 silver badges17 bronze badges 1- stackoverflow./questions/9713323/… – 7urkm3n Commented Oct 12, 2016 at 19:56
3 Answers
Reset to default 6One less-than-perfect option is:
const [name, age, is_male] = ['John Doe', 22, true];
Object.assign(this, {name, age, is_male});
or
Object.assign(this,
([name, age, is_male]) => ({name, age, is_male}))(['John, Doe', 22, true]));
Neither of these seems better than the three assignment statements.
What you are trying to do is to destructure into an object (in this case, one that you can assign
to this
. Various syntaxes have been proposed for this, such as
Object.assign(this,
{ [name, age, is_male] = ['John Doe', 22, true] });
and
Object.assign(this,
['John Doe', 22, true].{name, age, is_male});
but they have not gotten much traction in the language standards process.
Object.assign
will do that.
var obj = {
foo: 1,
copy: function() {
Object.assign(this, {
name: "John Doe",
age: 22,
is_male: true
});
}
}
obj.copy();
console.log(obj);
You can not do
this.[...
since this will give you an
Uncaught SyntaxError: Unexpected token [
but you can use the []
s to assign this.
-values:
[this.name, this.age, this.is_male] = ['John Doe', 22, true];