Q:

How to merge and flat arrays at the same time

I have two arrays of data, one has tree structure and another is just a nested array with details..
What I want to do now is to flat this details array and merge it to tree's structure.
Both details and tree have records with same unique ID.

   var tree = [{
     "Children": [{
       "Children": [],
       "ID": "1",
       "PendingChange": true,
     }],
     "ID": "22",
     "PendingChange": false,
   }];

   var details = [{
     "Address": {
       "Jurisdiction": {
         "Name": "United Kingdom"
       },
       "City": "Waltham Cross"
     },
     "ID": "1",
     "Name": "J"
   }];



   var finalArray = _.map(tree, function(e) {
     return _.extend(e, _.omit(_.findWhere(details, {
       ID: e.ID
     }), 'ID'));
   });

   console.log(finalArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Desired output
   var tree = [{
     "Children": [{
       "Children": [],
       "ID": "1",
       "PendingChange": true,
       "Name": "J"
       "Address_City": "Waltham Cross"
       "Address_Jurisdiction_Name": "United Kingdom"
     }],
     "ID": "22",
     "PendingChange": false,
   }];

Underscore is not a must, I am just stuck with it - https://jsfiddle.net/ey8hqn19/

A:

You could create recursive function with for...in loop that will loop deep tree object and then use find  to find object with same id in details and add properties.

var tree = [{
   "Children": [{
     "Children": [],
     "ID": "1",
     "PendingChange": true,
   }],
   "ID": "22",
   "PendingChange": false,
 }];

 var details = [{
   "Address": {
     "Jurisdiction": {
       "Name": "United Kingdom"
     },
     "City": "Waltham Cross"
   },
   "ID": "1",
   "Name": "J"
 }];

 function makeTree(data) {
   for (var i in data) {
     if (typeof data[i] == 'object') makeTree(data[i])
     if (i == 'ID') {
       var f = details.find(function(e) {
         return e.ID == data[i]
       })
       if (f) {
         Object.assign(data, {
           "Name": f.Name,
           "Address_City": f.Address.City,
           "Address_Jurisdiction_Name": f.Address.Jurisdiction.Name
         })
       }
     }
   }
 }

 makeTree(tree)
 console.log(tree)

