localStorage对象数组:如果唯一,则仅将新对象推送到数组中

时间:2016-02-18 16:02:00

标签: javascript jquery json local-storage javascript-objects

我已阅读了许多Stack Overflow问题,但似乎没有一个与我正在尝试解决的问题相关。

我有一个对象数组,我正在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上找到任何类似的东西。

2 个答案:

答案 0 :(得分:1)

您可以在此处使用一些解决方案。第一种方法是保留当前的对象数组,并在插入新的对象之前扫描它们以获取重复的餐馆名称。这看起来像这样:

// 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

答案 1 :(得分:0)

关联数组怎么样?您必须选择一个密钥:

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;