javascript - 如何从表示更改的对象数组中获取最终状态

标签 javascript arrays object timestamp swap

我有一组更改(对象),并且希望在完成所有更改后获得最终状态。

例如,进行以下更改:

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);

const item1 = {
  id: 'id1',
  timestamp: yesterday,
};
const item2 = {
  id: 'id2',
  timestamp: today,
};
const item3 = {
  id: 'id3',
  timestamp: tomorrow,
};

const changes = [
  {
    action: 'swap',
    item1,
    item2,
  },
  {
    action: 'swap',
    item1,
    item2: item3,
  },
]

我期待这个数组包含每个项目的最终状态:

const finalState = [
  {
    id: item1.id,
    timestamp: item3.timestamp,
  },
  {
    id: item2.id,
    timestamp: item1.timestamp,
  },
  {
    id: item3.id,
    timestamp: item2.timestamp,
  },
]

目前,我使用的逻辑是这个。但它无法正常工作。

export const convertChangesToFinalState = ({
  changes,
}): FinalChanges => {
  const finalState: {
    [id: string]: FinalChange;
  } = {};

  for (const { item1, item2 } of changes) {
    finalState[item1.id] = {
      id: item1.id,
      timestamp: new Date(finalState[item2.id]?.timestamp ?? item2.timestamp),
    };

    finalState[item2.id] = {
      id: item2.id,
      timestamp: new Date(finalState[item1.id]?.timestamp ?? item1.timestamp),
      // timestamp: new Date(new Date(item2.timestamp).getTime() !== new Date(finalState[item1.id]?.timestamp).getTime()? finalState[item1.id]?.timestamp : item1.timestamp),
    };
  }

  return Object.values(finalState);
};

你能帮我解决这个问题吗?

提前谢谢您!

最佳答案

item1存储在finalChanges中时,您无法再次读取此修改后的对象,否则您将访问新的更新值。在修改之前,您需要为每次迭代创建未修改对象的副本。

如果不存在,只需从主项中获取我们想要设置的值即可。

export const convertChangesToFinalState = ({
  changes,
}): FinalChanges => {
  const finalState: {
    [id: string]: FinalChange;
  } = {};

  for (const { item1, item2 } of changes) {
    const notAlteredItem = { ...finalState };
    finalState[item1.id] = {
      id: item1.id,
      timestamp: new Date(finalState[item2.id]?.timestamp ?? item2.timestamp),
    };

    finalState[item2.id] = {
      id: item2.id,
      timestamp: new Date(notAlteredItem[item1.id]?.timestamp ?? item1.timestamp)
    };
  }

  return Object.values(finalState);
};

检查此沙箱 https://codesandbox.io/s/zen-johnson-dkxk0?file=/src/index.js

关于javascript - 如何从表示更改的对象数组中获取最终状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70264066/

相关文章:

javascript - 通过嵌套键按对象数组进行分组

相当于 sed 的 javascript

javascript - 火狐浏览器 : how to serve sourcemaps for web extension

javascript - 有没有办法像默认导出一样使用 ES6 正常导出?

c - 如何在C中获取静态数组的地址

java - 检查类名不应包含特定文本

javascript - 同一页面上有多个 react 应用程序(组件)?

python - NumPy 多维数组迭代如何工作? (有无 nditer)

java - JPasswordField 转为字符串但无法比较

C++ 在 priority_queue 中使用 std::greater() 并排序