我在本地存储图像中有对象数组一些函数返回带有新数据的对象。我需要将新数据写入 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个赞
您应该从存储中获取数据,找到目标项的索引,将旧对象与新对象合并并将结果存储在特定索引处,然后将整个数组设置为相同的键。以下是最重要步骤的一部分:
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的链接,其中包含完整的示例(执行后检查本地存储)。
添加回答
举报
0/150
提交
取消