阿晨1998
2021-06-08 13:13:28
我在本地存儲圖像中有對象數(shù)組一些函數(shù)返回帶有新數(shù)據(jù)的對象。我需要將新數(shù)據(jù)寫入 localstorage 中的對象(通過 ID 標識)。我試過了,但是......見我下面的代碼 const result = { type: 'mobile', id: 'tsy152ivm', score: 55 } const links = JSON.parse(localStorage.getItem('links')); const item = links.find(item => item.id === result.id); //localStorage.setItem('links', JSON.stringify(item));
2 回答

哆啦的時光機
TA貢獻1779條經驗 獲得超6個贊
您應該從存儲中獲取數(shù)據(jù),找到目標項的索引,將舊對象與新對象合并并將結果存儲在特定索引處,然后將整個數(shù)組設置為相同的鍵。以下是最重要步驟的一部分:
const newData = {
id: 'ID_2',
NEW_DATA: 'NEW_DATA'
};
/**
* Get old data from storage
*/
const dataFromStorage = JSON.parse(localStorage.getItem('links'));
/**
* Merge old object with a new one (find by ID)
*/
const index = dataFromStorage.findIndex(d => d.id === newData.id);
dataFromStorage[index] = Object.assign({}, dataFromStorage[index], newData)
/**
* Update full array in storage
*/
localStorage.setItem('links', JSON.stringify(dataFromStorage));
這是一個指向JSFIDDLE的鏈接,其中包含完整的示例(執(zhí)行后檢查本地存儲)。
添加回答
舉報
0/150
提交
取消