假设我从这开始:
var shippingAddresses = [{ "firstname": "Kevin","lastname": "Borders","address1": "2201 N Pershing Dr","address2": "Apt 417","city": "Arlington","state": "VA","zip": "22201","country": "US" },{ "firstname": "Dan","lastname": "Hess","address1": "304 Riversedge Dr","address2": "","city": "Saline","state": "MI","zip": "48176","country": "US" }];
我用这个来填写一个表单.用户可以编辑条目或添加新条目.我需要防止他们添加重复.
问题是我正在序列化的表单的结构以及这些值从数据库中返回的顺序是不一样的,所以有机会将一个项目插入到这个数组中,格式如下:
{ "country": "US","firstname": "Kevin","state": "VA" }
哪个与第一个条目相同,只是以不同的顺序排列.
我正在加载underscorejs,所以如果有办法处理它与该库将是伟大的.我也使用jQuery,如果这有帮助.
在这一点上,我不知道如何进行.任何帮助将不胜感激.
解决方法
Underscore
findWhere
function完全符合您所需要的 – 它不是按对象标识搜索的索引,而是搜索其属性与输入值相同的对象.
if (_.findWhere(shippingAddresses,toBeInserted) == null) { shippingAddresses.push(toBeInserted); }