本地存储对象数组:仅将新对象推送到数组中(如果唯一)

localStorage Array of Objects: Only push new object into array if unique

本文关键字:对象 数组 唯一 如果 新对象 存储      更新时间:2023-09-26

我已经阅读了许多堆栈溢出问题,但似乎没有一个与我试图解决的问题相关。

我有一个保存在 localStorage 中的对象数组,如下所示(此示例仅包含两个):

[
  {
    "image": "http://example-image.jpg",
    "restaurantName": "Elena's L'Etoile",
    "parentLocation": "London",
    "areaLocation": "West End of London",
    "pageLink": "http://example-address1"
},
  {
    "image": "http://example-image2.jpg",
    "restaurantName": "Pied a Terre",
    "parentLocation": "London",
    "areaLocation": "West End of London",
    "pageLink": "http://example-address2"
  }
]

每次用户访问页面时,都会从页面中提取数据,并创建一个餐厅对象,如下所示:

 var restaurant = {"image": $image, "restaurantName": $restaurantName, "parentLocation": $parentLocation, "areaLocation": $areaLocation, "pageLink": $pageLink};

然后将其存储到现有的对象数组(上图)中:

existingRestaurants.push(restaurant);

问题是,如果用户两次访问同一页面,则会在数组中推送重复的对象。如何确保只有唯一的对象被推送到数组中?

我研究过的方法:使用 $.each、$.inArray、$.grep。我认为最简单的方法是遍历现有餐厅数组中的所有对象,并将"restaurantName"键的值与新餐厅对象中的相应值进行比较。

但是我无法在堆栈溢出上找到其他类似的东西。

这里有一些解决方案。第一种方法是保留您当前的对象数组,并在插入新餐厅名称之前扫描所有对象以查找重复的餐厅名称。这看起来像这样:

// assuming 'arr' is the variable holding your data
var matches = $.grep(arr, function(obj) {
    return obj.restaurantName == $restaurantName;
});
if (matches.length) {
    console.log('Duplicate found, item not added');
} else {
    var restaurant = {
        "image": $image,
        "restaurantName": $restaurantName,
        "parentLocation": $parentLocation,
        "areaLocation": $areaLocation,
        "pageLink": $pageLink
    };
    arr.push(restaurant);
}

工作示例

或者,最好是,

您可以将数据结构修改为一个对象,键是无法复制的值;在这种情况下,餐厅名称:

var arr = {
    "Elena's L'Etoile": {
        "image": "http://example-image.jpg",
        "parentLocation": "London",
        "areaLocation": "West End of London",
        "pageLink": "http://example-address1"
    },
    "Pied a Terre": {
        "image": "http://example-image2.jpg",
        "parentLocation": "London",
        "areaLocation": "West End of London",
        "pageLink": "http://example-address2"
    }
};
if (arr[$restaurantName]) {
    console.log('Duplicate found, item not added');
} else {
    var restaurant = {
        "image": $image,
        "parentLocation": $parentLocation,
        "areaLocation": $areaLocation,
        "pageLink": $pageLink
    };
    arr[$restaurantName] = restaurant;
}

工作示例

关联数组怎么样?不过,您必须选择一个键:

var restaurant0 = {"image": "http://example-image.jpg", "restaurantName": "Elena's L'Etoile", "parentLocation": "London", "areaLocation": "West End of London", "pageLink": "http://example-address1" };
var restaurant1 = {"image": "http://example-image2.jpg", "restaurantName": "Pied a Terre", "parentLocation": "London", "areaLocation": "West End of London", "pageLink": "http://example-address2"};
var existingRestaurants = {};
existingRestaurants["id0"] = restaurant0;
existingRestaurants["id1"] = restaurant1;