【问题标题】:How to concatenate two array objects using jquery without adding duplicates如何使用 jquery 连接两个数组对象而不添加重复项
【发布时间】:2011-08-17 21:11:13
【问题描述】:

我有两个数组对象:

 var arr1 =[{product_id: 2, name: 'stack'}, {product_id: 3, name: 'overflow'}];

 var  arr2 = [{product_id: 2, name: 'popo'},{product_id: 6, name: 'foo'}];

我做 jquery 如下:

$.each(arr1 , function(){ 
      var productId = this.product_id;
       $.each(arr2 , function(productId){
        if(this.product_id != productId){
           arr2.push(this);
        }
       }); 
   });

最后

arr2 必须看起来像

     var  arr2 = [{product_id: 2, name: 'stack'}, {product_id: 3, name: 'overflow'},
             {product_id: 6, name: 'foo'}]

我在做正确的 jquery 编码吗?

【问题讨论】:

  • 有效吗?你测试了吗?....

标签: jquery


【解决方案1】:

$.extend(arr1,arr2)

这将从 arr2 复制(并覆盖重复项)到 arr1。

参考:http://api.jquery.com/jQuery.extend/

【讨论】:

    【解决方案2】:
    $.extend(true, arr1, arr2);
    

    Extend 将两个对象/数组连接到第一个对象中。

    【讨论】:

    • 第一个参数用于确保它进行深度递归,并检查数组中的值。
    • 如果属性相同,则保留。
    猜你喜欢
    • 2014-02-22
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2020-06-26
    • 2016-08-25
    相关资源
    最近更新 更多