第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何更新/更改數(shù)組中的對象?

如何更新/更改數(shù)組中的對象?

阿晨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í)行后檢查本地存儲)。


查看完整回答
反對 回復 2021-06-11
  • 2 回答
  • 0 關注
  • 238 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號