【发布时间】:2023-03-13 11:47:01
【问题描述】:
如果之前有人问过这个问题,我深表歉意,但我似乎无法从这里的其他帖子中找到解决方案。
我正在尝试在本地存储中构建一个 json 数组(这很好),但想在添加新值之前检查一个条目是否已经存在。
Json 本身
[{"title":"title1","url":"somefile1.pdf","background":"bg1.png"},
{"title":"title2","url":"somefile2.pdf","background":"bg2.png"},
{"title":"title3","url":"somefile3.pdf","background":"bg3.png"}]
现在我将如何查询数组以确保只添加唯一条目?
下面是添加到数组的代码
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'title': title,
'url': url,
'background': background
};
// Need to check the newItem is unique here //
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
在设置 localstorage 对象之前,我想我可以使用 jquery unique 函数来代替
var cleanedItems = $.unique(oldItems);
localStorage.setItem('itemsArray', JSON.stringify(cleanedItems));
但这没有用......
【问题讨论】:
-
不要使用数组,使用键是唯一标识元素的任何属性的对象。
-
对象键比较不简单——github.com/joyent/node/blob/…
标签: javascript json local-storage