在再次分配该对象时,如何防止覆盖先前设置的属性?

时间:2017-08-01 09:37:18

标签: javascript ecmascript-6

顺便说一下,在执行此操作时,如何在hasChanged中保持apiAction的值?

let apiAction = {}

function firstFunction () {
  apiAction.form.hasChanged = true
}


function secondFunction () {
  apiAction = {
    name: 'updateBuilding',
    form: this.buildingForm,
    clearFields: true
  } // this will remove hasChanged
}

firstFunction()
secondFunction()

1 个答案:

答案 0 :(得分:2)

没有特别优雅的方式,因为hasChangedform的属性,而不是apiAction

您可以通过form浅层克隆hasChanged并将Object.assign设置为当前值:

secondFunction () {
  apiAction = {
    name: 'updateBuilding',
    form: Object.assign(
            {},
            this.buildingForm,
            {hasChanged: apiAction.form && apiAction.form.hasChanged || false}
    ),
    clearFields: true
  }
}

(我假设如果apiAction没有form,或form没有hasChanged,则该值应为false。)

...或保留相同的form对象并设置其属性:

secondFunction () {
  if (apiAction.form) {
    this.buildingForm.hasChanged = apiAction.form.hasChanged;
  }
  apiAction = {
    name: 'updateBuilding',
    form: this.buildingForm,
    clearFields: true
  }
}