【问题标题】:Ensuring Unique Json确保唯一的 Json
【发布时间】: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));

但这没有用......

【问题讨论】:

标签: javascript json local-storage


【解决方案1】:

您必须遍历从本地存储解析的数组中的每个项目,并使用新项目执行对象相等性测试。

对象相等性测试并不像obj1 == obj2那么简单。

以下是一些帮助您入门的参考资料

通过使用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));

【讨论】:

  • 绝对棒极了-完全按照我的需要工作,非常感谢..我已经为此苦恼了好几个小时..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 2011-01-20
  • 2018-11-25
  • 1970-01-01
  • 2014-09-05
  • 1970-01-01
相关资源
最近更新 更多