如果之前有人问过这个问题,我深表歉意,但我似乎无法从这里的其他帖子中找到解决方案。
我正在尝试在本地存储中构建一个 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));
但这没有用...
最佳答案
您必须循环遍历从本地存储解析的数组中的每个项目,并使用新项目执行对象相等性测试。
对象相等性测试并不像obj1 == obj2
那么简单。
这里有一些帮助您入门的引用
- http://procbits.com/2012/01/19/comparing-two-javascript-objects
- https://github.com/joyent/node/blob/e4cef1a0833e6d677298600e205a142d15639bf2/lib/assert.js#L205-L247
- http://stamat.wordpress.com/2013/06/22/javascript-object-comparison/
- http://underscorejs.org/docs/underscore.html#section-84
通过使用 JSON.stringify
将新对象作为 JSON 字符串与旧数组中作为 JSON 字符串的对象进行比较,以下内容可能最终适合您。
function objInArr(newObj, oldItems) {
var newObjJSON = JSON.stringify(newObj);
for (var i = 0, l = oldItems.length; i < l; i++) {
if (JSON.stringify(oldItems[i]) === newObjJSON) {
return true;
}
}
return false;
}
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'title': title,
'url': url,
'background': background
};
// Need to check the newItem is unique here
if (!objInArr(newItem, oldItems)) {
oldItems.push(newItem);
}
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
关于javascript - 确保 Json 唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19870631/