首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何更新/更改数组中的对象?

如何更新/更改数组中的对象?
EN

Stack Overflow用户
提问于 2019-05-27 01:27:15
回答 2查看 199关注 0票数 2

我在本地存储image中有对象的数组

一些函数返回带有新数据对象。我需要将新数据写入本地存储中的对象(通过ID标识)。

我试过了但是..。请参阅下面的代码

代码语言:javascript
复制
      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));
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-27 01:41:36

使用.findIndex()查找要修改的对象的索引,并使用Object.assign()更新对象的属性。

代码语言:javascript
复制
let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);

const updated = [...arr.slice(0, index),Object.assign({}, arr[index], { id: result.id, name: 'Samantha' }),
...arr.slice(index + 1)
]

console.log(updated);

或者使用索引直接修改对象。

代码语言:javascript
复制
let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);


arr[index] = Object.assign({}, arr[index], { name: 'Samantha'})

console.log(arr);

票数 1
EN

Stack Overflow用户

发布于 2019-05-27 01:55:08

您应该从存储中获取数据,找到目标项的索引,将旧对象与新对象合并并将结果存储在特定的索引处,然后将整个数组设置为相同的键。以下是最重要的步骤的一部分:

代码语言:javascript
复制
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链接(执行后检查本地存储)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56315843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档