javascriptobjectcloneuse-strict

Javascript - Assign (not clone) a large object to a new variable to reduce its name


I want to assign a large object to a new variable to reduce its name, but I have an error : "realEstateProjectFundReuse" is read-only

const realEstateProjectFundReuse = this.project.realEstateProjectMotivation.realEstateProjectFundReuse
    realEstateProjectFundReuse = omit(realEstateProjectFundReuse, [this.fundReuseTypeChoose(), 'description'])

But this syntax works

const realEstateProjectFundReuse = this.project.realEstateProjectMotivation.realEstateProjectFundReuse
this.project.realEstateProjectMotivation.realEstateProjectFundReuse = omit(realEstateProjectFundReuse, [this.fundReuseTypeChoose(), 'description'])

Solution

  • Using the keyword const you create a constant, which cannot get assigned another value (like in your second line).

    But even if you would use let to define a variable, setting it to a new value would not change the original object. The reason therefore is that omit creates a new object. realEstateProjectFundReuse would then point to the newly created object while this.project.realEstateProjectMotivation.realEstateProjectFundReuse still points to the old one.

    One option would be the following:

    const projectMotivation = this.project.realEstateProjectMotivation;
    projectMotivation.realEstateProjectFundReuse = omit(projectMotivation.realEstateProjectFundReuse, [this.fundReuseTypeChoose(), 'description'])