我有一系列更改(物件),并希望在進行所有更改后獲得最終狀態。
例如,具有以下更改陣列:
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);
};
你能幫我解決這個問題嗎?
先感謝您!
uj5u.com熱心網友回復:
當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: notAlteredItem[item1.id]?.timestamp ?? item1.timestamp
};
}
return Object.values(finalState);
};
檢查這個沙箱https://codesandbox.io/s/zen-johnson-dkxk0?file=/src/index.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/376509.html
標籤:javascript 数组 目的 时间戳 交换
上一篇:如何遍歷物件內部的物件