首页 > 解决方案 > 当我在 forEach 循环中重新分配属性时,为什么我的对象没有改变?

问题描述

我正在从 http 后端的 RX/JS 调用中获取对象数组。它返回一个我正在尝试使用的对象。我正在使用 for 循环对此对象进行更改(在此示例中,我正在尝试,.forEach因为我尝试了许多不同的东西,但它们似乎都不起作用。

当我运行代码时,我遇到了一个非常奇怪的问题。如果我返回属性的值,我会得到新值(即correctionQueued返回为 true 等),但在下一行,当我返回对象时,这些相同的值与原始值相同(correctionQueued=== false等)但是,correctionStatus(从http的原始对象上不存在)设置得很好。

我不明白如何 array[index].correctionQueued返回 true,但 array[index]返回一个correctionQueued为 false 的对象。

checklistCopy循环之后,原始数组forEachcorrectionStatus

我尝试过使用 for of、for in 和 .forEach。我使用索引来更改原始数组,结果始终相同。预先存在的属性不会改变,会添加新的属性。我什至尝试处理对象的副本,以防从 rxjs 返回的对象有什么特别之处,但无济于事。

    checklistCopy.forEach((checklistItem, index, array) => {
      if (checklistItem.crCode.isirName === correctionSetItem) {
        array[index].correctionQueued = true;
        array[index].correctionValue = mostRecentCorrection.correctionValue;
        array[index].correctionStatus = mostRecentCorrection.status;
        console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
        console.log(array[index]);
      }
    }
    );

我没有收到错误,但我得到..

原始对象是:

correctionQueued: false;
correctionValue: JAAMES;

--

console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
true JAMES            SENT

但是当我打印整个对象时:

console.log(array[index]);

correctionQueued: false;
correctionValue: JAAMES;
correctionStatus: "SENT'; <-- This is set correctly but does not exist on original object.

标签: arraystypescriptforeachrxjs

解决方案


您的输出对我来说也没有意义,但清理您的代码可能会对您有所帮助。试试这个:

checklistCopy.forEach(checklistItem => {
  checklistItem.correctionQueued = checklistItem.crCode.isirName === correctionSetItem;
  if (checklistItem.correctionQueued) {
      checklistItem.correctionValue = mostRecentCorrection.correctionValue;
      checklistItem.correctionStatus = mostRecentCorrection.status;
      console.log('checklistItem', checklistItem)
    }
  }
);

推荐阅读