只有唯一对象添加到在JavaScript中的数组 [英] add only unique objects to an array in JavaScript

查看:174
本文介绍了只有唯一对象添加到在JavaScript中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我开始与此:

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

我用这个prepopulate一种形式。用户可以编辑条目或添加新的。我需要$ P $从增加重复pvent他们。

I use this to prepopulate a form. Users can edit entries or add new ones. I need to prevent them from adding duplicates.

问题是,我序列化的形式和这些值从数据库返回的顺序结构是不一样的,所以,我将插入一个项目到这个数组的格式如下机会:

The issue is that the structure of the form that I am serializing and the order these values are returned from the database are not the same, so there is a chance that I will insert an item into this array with the following format:

                            {
                                "country": "US",
                                "firstname": "Kevin",
                                "lastname": "Borders",
                                "address1": "2201 N Pershing Dr",
                                "address2": "Apt 417",
                                "zip": "22201",                                    
                                "city": "Arlington",
                                "state": "VA"
                            }

这是相同的第一个条目,用命令不同。

Which is the same as the first entry, just ordered differently.

我加载underscorejs,因此,如果有一种方法与该库将是巨大的来处理它。我还使用jQuery的是否有帮助。

I am loading underscorejs, so if there's a way to handle it with that library that would be great. I'm also using jQuery if that helps.

在这一点上我不知道如何着手。任何帮助将大大AP preciated。

At this point I'm not sure how to proceed. Any help would be greatly appreciated.

推荐答案

findWhere 功能不正是你所需要的 - 它是不是由对象标识的的indexOf 搜索,但搜索的对象,其属性有作为输入相同的值

The Underscore findWhere function does exactly what you need - it's not an indexOf search by object identity, but searches objects whose properties have the same values as the input.

if (_.findWhere(shippingAddresses, toBeInserted) == null) {
    shippingAddresses.push(toBeInserted);
}

这篇关于只有唯一对象添加到在JavaScript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆