如何将值分配给对象数组的元素和return更新的对象打字稿

How to assign the value to the element of an array of the object and return the updated object typscript

我正在尝试 return 'detailsState' 的 Current 更新值。 我试过如下:

  export function GetDetailsPayload(payload: INFO, detailsState: DetailsViewmodel, isSaved: boolean) {
  if (payload && payload.SSN && detailsState && detailsState.INFODetail && detailsState.INFODetail.Active) {

    detailsState.INFODetail.Active = payload;
    if (isSaved) {
      detailsState.INFODetail.Current.map((c, i) => {
        if (c.Id == detailsState.INFODetail.Active.Id) {
          c = payload;
          return c;
        }

      });

    }
  }
  return detailsState;
}

实际结果: detailsState.INFODetail.Current 相同而不是负载。

预期结果: detailsState.INFODetail.Current 当数组中的元素之一满足条件时,具有有效载荷的值。

谢谢!

您的这部分代码:

detailsState.INFODetail.Current.map((c, i) => {
    if (c.Id == detailsState.INFODetail.Active.Id) {
        c = payload;
        return c;
    }
});

您映射了 .Current 中的项目,但实际上并未对映射结果执行任何操作。您可能打算改为这样做:

detailsState.INFODetail.Current = detailsState.INFODetail.Current.map((c, i) => {
    if (c.Id == detailsState.INFODetail.Active.Id) {
        c = payload;
        return c;
    }
});

请注意,当您不在映射器中 return c 时,它将用 undefined 替换某些元素。您可能打算 return 原始值,否则:

detailsState.INFODetail.Current = detailsState.INFODetail.Current
    .map((c, i) => (c.Id == detailsState.INFODetail.Active.Id) ? payload : c);