我已阅读了许多 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。我认为最简单的方法是循环访问现有餐厅数组中的所有对象,并将“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);
}
或者,最好,您可以将数据结构修改为一个对象,其中键是不能重复的值;在本例中,餐厅名称:
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;
}
关于javascript - localStorage 对象数组 : Only push new object into array if unique,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486394/