如何同时合并和平面数组

时间:2017-01-18 12:03:36

标签: javascript arrays

我有两个数据数组,一个是树结构,另一个是带有详细信息的嵌套数组。

我现在要做的是平放这个细节数组并将其合并到树的结构中。

详细信息和树都有相同唯一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>

所需的输出

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

下划线不是必须的,我只是坚持下去 - https://jsfiddle.net/ey8hqn19/

1 个答案:

答案 0 :(得分:1)

您可以使用for...in循环创建递归函数,循环深树对象,然后使用find查找具有相同ID的对象并添加属性。

&#13;
&#13;
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)
&#13;
&#13;
&#13;