How to merge two array of objects

前端 未结 2 1589
孤街浪徒
孤街浪徒 2020-12-20 23:04

I have two array of objects like following:

result = [{id:24, name:\"xyz\"}, {id:45,name:\"tze\"}]
moreDetails = [{id:         


        
相关标签:
2条回答
  • 2020-12-20 23:23

    You can use a for loop, in this case extending one of the arrays' elements is better than creating another array:

    for (var i = 0; i < result.length; i++) {
        result[i].name2 = moreDetails[i].name2;
    }
    

    http://jsfiddle.net/9uchU/

    In case that target elements have different indices:

    for (var i = 0; i < result.length; i++) {
        var c = result[i],
            // filtering the second array based on the `id` 
            // of the current element 
            m = moreDetails.filter(function(elem) {
                 return elem.id === c.id;
            })[0];
        c.name2 = m ? m.name2 : 'not defined';
    }
    

    Edit: Based on your last edit, as @Blender mentions, you can also use jQuery $.extend() utility function:

    $.extend(result, moreDetails);
    
    0 讨论(0)
  • 2020-12-20 23:37
    <html>
    <head><title></title>
    <script src="http://code.jquery.com/jquery-1.10.0.min.js" ></script>
    </head>
    <body>
    
    <script>
        function findElement(arr, propName, propValue) {
          for (var i=0; i < arr.length; i++){
            if (arr[i][propName] == propValue){
              return arr[i];
            }
          }
        }
    
        var result = [{id:24, name:"xyz"}, {id:45,name:"tze"}];
        var moreDetails= [{id:24, name2:"hyi"}, {id:45, name2:"tikw"}];
        var mergedResult = result;
    
        for (var i = 0; i<result.length;i++ ) {
          //mergedResult[i].name2 = findElement(moreDetails, "id", result[i].id).name2
        $.extend(mergedResult[i],findElement(moreDetails, "id", result[i].id));
        } 
    
        mergedResult;
    </script>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题