localStorage 对象数组:如果唯一,则只将新对象推入数组

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

我已经通读了许多 Stack Overflow 问题,但 none 似乎与我要解决的问题相关。

我在 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。我认为最简单的方法是遍历 existingRestaurants 数组中的所有对象,并将 "restaurantName" 键的值与新餐厅对象中的相应值进行比较。

但我无法在 Stack Overflow 上找到任何其他类似内容。

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

// 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);
}

Working example

或者,最好是,您可以将您的数据结构修改为一个对象,其键是不能重复的值;在这种情况下,餐厅名称:

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;
}

Working example

关联数组怎么样?不过,您必须 select 一把钥匙:

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;