Skip to content Skip to sidebar Skip to footer

How Can I Use This In The Left Side Of The Object Destructuring Assignment?

(This question is not specific to Vue, but it is in a Vue project, that is why the strange use of the this in front of the functions and variables.) I have a function that returns

Solution 1:

You can spell out the destructuring targets, instead of implicitly creating const variables:

({
  primaryNumber: this.primaryNumber,
  typeOfExpression: this.typeOfExpression
} = this.findPrimaryAndType(
  this.naturalExpressionYearOfBirth,
  this.gender,
));

Of course that's not very helpful in terms of conciseness. If those two properties are the only ones on the result object, you can however use Object.assign:

Object.assign(this, this.findPrimaryAndType(
  this.naturalExpressionYearOfBirth,
  this.gender,
));

Solution 2:

Your workaround is the correct way to do this (at least from a pure Javascript perspective, not sure how Vue handles this). You can make it slightly shorter by using Object.assign:

const { primaryNumber, typeOfExpression } = this.findPrimaryAndType(
    this.naturalExpressionYearOfBirth,
    this.gender,
);
Object.assign(this, { primaryNumber, typeOfExpression });

Or, if you wanted to copy all the returned properties from findPrimaryAndType to the current instance, you could skip the destructuring altogether:

const { naturalExpressionYearOfBirth, gender } = this;
Object.assign(this, this.findPrimaryAndType(naturalExpressionYearOfBirth, gender));

Post a Comment for "How Can I Use This In The Left Side Of The Object Destructuring Assignment?"