【发布时间】:2016-05-30 21:50:17
【问题描述】:
我已经阅读了许多 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。我认为最简单的方法是遍历现有Restaurants 数组中的所有对象,并将“restaurantName”键的值与新餐厅对象中的相应值进行比较。
但我在 Stack Overflow 上找不到其他类似的东西。
【问题讨论】:
-
从数组切换到以餐厅名称或页面链接为键的对象。
-
使用
$.grep或$.each显示您的尝试,以便我们帮助指出问题。您可能试图比较两个不共享相同引用的对象。$.inArray绝对不适合这个 -
.filter或.some可用于检查对象是否已存在。不需要 jquery 相关的东西。 some -
@JohannesJander 是不是不能把数据的整体结构保持为一个数组来实现我想做的事情?
标签: javascript jquery json local-storage javascript-objects