【问题标题】:Merging two JSON Objects under condition for two JSON Arrays在两个 JSON 数组的条件下合并两个 JSON 对象
【发布时间】:2016-03-22 15:49:08
【问题描述】:

我在将两个 JSON 对象(每个来自另一个数组)合并到一个新 JSON 对象中时遇到问题,在一个新数组中(合并必须在给定条件下发生)。

例子:

第一个数组:

var array1 = [{box:123,name:xxx,amount:xxx},{box:321,....},...]
var array2 = [{_id:123,look:xxx,title:myBox1},{_id:321,.....},...]
var newArray = [{box:123,name:xxx,amount:xxx,look:xxx,title:myBox1},...]

我基本需要的东西: 遍历 Array1,遍历 Array2。 if box (array1) == _id (array2) 将两个对象的所有属性合并为一个新的 JSON 并将其放入新数组的第一个空闲槽中。

我希望该示例有助于了解我正在尝试做什么。什么是最好的解决方案?

通常,两个数组中的第一个属性也是需要比较的属性,但是如果我想比较例如解决方案也可以工作的话,这是可以的。第一个数组中的第一个属性与第二个数组中的第三个属性。

希望有人能帮帮我!

【问题讨论】:

    标签: javascript jquery arrays json merge


    【解决方案1】:

    您可以通过两个循环来实现这一点。第一个遍历存储在array1 中的对象,第二个遍历array2 中匹配对象的属性。试试这个:

    var newArray = [];
    for (var i = 0; i < array1.length; i++) {
        var obj = array1[i];
        if (array2[i] && obj.box == array2[i]._id) {
            for (key in array2[i]) {
                obj[key] = array2[i][key];
            }
            newArray.push(obj);
        }
    };
    

    Example fiddle

    【讨论】:

      【解决方案2】:

      你可以试试这个:

       array3=[]
      for(item1 in array1){
                for(item2 in array2){
               if(item1.box == item2._id)
                 array3.push(Merge_objects(item1,item2))
               }
            }
      
      
      
          function Merge_objects(obj1,obj2){
              var obj3 = {};
              for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
              for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
              return obj3;
          }
      

      【讨论】:

        【解决方案3】:

        下面的函数可以做到这一点。它比其他答案稍长,但更通用(您可以指定哪些属性是 id,而不是坚持使用 box_id)并且不会以任何方式修改原始数组。它也不依赖于两个数组中项目的顺序是否相同(即box:123 可以在array1 的索引1 中,_id:123 可以在array2 的索引3 中)。

        /*
            a1 = the first array of objects
            id1 = the name of the property of each object in a1 that is its id
            a2 = the second array of objects
            id2 = the name of the property of each object in a2 that is its id
        */
        function combine(a1, id1, a2, id2) {
            // create our new array to return
            var newArray = []
            // iterate over a1 (the outer loop)
            for(var i = 0, l = a1.length; i < l; i++) {
                var outer = a1[i]; // get the current object for this iteration
                // iterate over a2 (the inner loop)
                for(var j = 0, m = a2.length; j < m; j++) {
                    var inner = a2[j]; // get the current object for this iteration of the inner loop
                    if(outer[id1] == inner[id2]) { // compare the ids for the outer and inner objects
                        var o = {}; // create a new blank object to add to newArray
                        o[id1] = outer[id1]; // set its id (using the same property name as that of a1)
                        for(var prop in outer) { // iterate over properties
                            if(prop != id1) { // ignore the id property, but copy the others
                                o[prop] = outer[prop]
                            }
                        }
        
                        for(var prop in inner) {
                            if(prop != id2) {
                                o[prop] = inner[prop]
                            }
                        }
        
                        // add this object to newArray
                        newArray.push(o);
                    }
                }
            }
        
            // return newArray
            return newArray;
        }
        

        用法:

        var array1 = [{box:123,name:'Name 1',amount:1},{box:321,name:'Name 2',amount:2}]
        var array2 = [{_id:123,look:'Look 1',title:'My box 1'},{_id:321,look:'Look 2',title:'My box 2'}]
        var newArray = combine(array1, "box", array2, "_id");
        

        【讨论】:

        • 像魅力一样工作!谢谢!
        【解决方案4】:

        您可以为此使用Array.prototype.mapArray.prototype.reduce。记住time complexity!如果对象是 uniq 键(_idbox)并且数组长度相等:

        // TODO: implement your own comparator based on _id/box type
        var first = array1.sort((a, b) => a._id - b._id);
        var second = array2.sort((a, b) => a.box - b.box);
        var merged = sorted_first.map((item, index) => Object.assign(item, second[index]));
        

        您可以轻松地将其调整为不同长度的情况等等,但您确实需要先了解您的数据。

        【讨论】:

          【解决方案5】:
                  Creating the dummy datas, this is what the programming should be:
                  var a = [{
                      id: 1,
                      name: 'name1',
                    }, {
                      id: 2,
                      name: 'name2',
                    }, {
                      id: 3,
                      name: 'name3',
          
                    }];
          
                    var b = [{
                      id: 1,
                      look: 'look1'
                    }, {
                      id: 321,
                      look: 'look321'
                    }, {
                      id: 3,
                      look: 'look3',
          
                    }
          
                    ];
          
                  // put the object id : 321 and look : look321 into array a from array b
                    for (var i = 0; i < b.length; i++) {
                      var obj_b= b[i];
                      var id_b= b[i].id;
                      var idNotFound = true;
                      a.forEach(function(rowOfA){
                      var id_a = rowOfA.id;
                      if(id_a == id_b ){
                          idNotFound = false;
                      }
                      });
                      if( idNotFound ){
          
                          a.push( b[i] );
                      }//if
          
                  }
                  // merge the objects with same ids into array a
                      for (var i = 0; i < a.length; i++) {
                          var id_a = a[i].id;
                          var found = false;
                          for (var j = 0; j < b.length; j++) {
                              var id_b= b[j].id;
                              if(id_a == id_b){
                                found = b[j];
                              }//if
          
                          }//for2
                          if (found) {
                              a[i]["look"] = found.look;
                          }//if
                      }//for1
          
                      console.log('aa=>',a);
              /*
          The output is  aa=> [ { id: 1, name: 'name1', look: 'look1' },
                { id: 2, name: 'name2' },
                { id: 3, name: 'name3', look: 'look3' },
                { id: 321, look: 'look321' } ]
             */
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-01-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-17
            • 1970-01-01
            • 2021-07-21
            相关资源
            最近更新 更多