Node.js中如何合并两个复杂对象详解


Posted in Javascript onDecember 31, 2016

前言

相信大家都知道在通常情况下,在Node.js中我们可以通过underscore的extend或者lodash的merge来合并两个对象,但是对于像下面这种复杂的对象,要如何来应对呢?下面来一起学习学习吧。

Node.js合并两个复杂对象

例如我有以下两个object:

var obj1 = {
 "name" : "myname",
 "status" : 0,
 "profile": { "sex":"m", "isactive" : true},
 "strarr":["one", "three"],
 "objarray": [
 {
  "id": 1,
  "email": "a1@me.com",
  "isactive":true
 },
 {
  "id": 2,
  "email": "a2@me.com",
  "isactive":false
 }
 ]
};

var obj2 = {
 "name" : "myname",
 "status" : 1,
 "newfield": 1,
 "profile": { "isactive" : false, "city": "new York"},
 "strarr":["two"],
 "objarray": [
 {
  "id": 1,
  "isactive":false
 },
 {
  "id": 2,
  "email": "a2modified@me.com"
 },
 {
  "id": 3,
  "email": "a3new@me.com",
  "isactive" : true
 }
 ]
};

希望合并之后的结果输出成下面这样:

{ name: 'myname',
 status: 1,
 profile: { sex: 'm', isactive: false, city: 'new York' },
 strarr: [ 'one', 'three', 'two' ],
 objarray: 
 [ { id: 1, email: 'a1@me.com', isactive: false },
 { id: 2, email: 'a2modified@me.com', isactive: false },
 { id: 3, email: 'a3new@me.com', isactive: true } ],
newfield: 1 }

通过underscore或者lodash现有的方法我们无法实现上述结果,那只能自己写代码来实现了。

function mergeObjs(def, obj) {
 if (!obj) {
 return def;
 } else if (!def) {
 return obj;
 }

 for (var i in obj) {
 // if its an object
 if (obj[i] != null && obj[i].constructor == Object)
 {
  def[i] = mergeObjs(def[i], obj[i]);
 }
 // if its an array, simple values need to be joined. Object values need to be remerged.
 else if(obj[i] != null && (obj[i] instanceof Array) && obj[i].length > 0)
 {
  // test to see if the first element is an object or not so we know the type of array we're dealing with.
  if(obj[i][0].constructor == Object)
  {
  var newobjs = [];
  // create an index of all the existing object IDs for quick access. There is no way to know how many items will be in the arrays.
  var objids = {}
  for(var x= 0, l= def[i].length ; x < l; x++ )
  {
   objids[def[i][x].id] = x;
  }

  // now walk through the objects in the new array
  // if the ID exists, then merge the objects.
  // if the ID does not exist, push to the end of the def array
  for(var x= 0, l= obj[i].length; x < l; x++)
  {
   var newobj = obj[i][x];
   if(objids[newobj.id] !== undefined)
   {
   def[i][x] = mergeObjs(def[i][x],newobj);
   }
   else {
   newobjs.push(newobj);
   }
  }

  for(var x= 0, l = newobjs.length; x<l; x++) {
   def[i].push(newobjs[x]);
  }
  }
  else {
  for(var x=0; x < obj[i].length; x++)
  {
   var idxObj = obj[i][x];
   if(def[i].indexOf(idxObj) === -1) {
    def[i].push(idxObj);
   }
  }
  }
 }
 else
 {
  def[i] = obj[i];
 }
 }
 return def;}

将上述代码稍作改进,我们可以实现在合并过程中将Number类型的值自动相加。

function merge(def, obj) {
 if (!obj) {
  return def;
 }
 else if (!def) {
  return obj;
 }

 for (var i in obj) {
  // if its an object
  if (obj[i] != null && obj[i].constructor == Object)
  {
   def[i] = merge(def[i], obj[i]);
  }
  // if its an array, simple values need to be joined. Object values need to be re-merged.
  else if(obj[i] != null && (obj[i] instanceof Array) && obj[i].length > 0)
  {
   // test to see if the first element is an object or not so we know the type of array we're dealing with.
   if(obj[i][0].constructor == Object)
   {
    var newobjs = [];
    // create an index of all the existing object IDs for quick access. There is no way to know how many items will be in the arrays.
    var objids = {}
    for(var x= 0, l= def[i].length ; x < l; x++ )
    {
     objids[def[i][x].id] = x;
    }

    // now walk through the objects in the new array
    // if the ID exists, then merge the objects.
    // if the ID does not exist, push to the end of the def array
    for(var x= 0, l= obj[i].length; x < l; x++)
    {
     var newobj = obj[i][x];
     if(objids[newobj.id] !== undefined)
     {
      def[i][x] = merge(def[i][x],newobj);
     }
     else {
      newobjs.push(newobj);
     }
    }

    for(var x= 0, l = newobjs.length; x<l; x++) {
     def[i].push(newobjs[x]);
    }
   }
   else {
    for(var x=0; x < obj[i].length; x++)
    {
     var idxObj = obj[i][x];
     if(def[i].indexOf(idxObj) === -1) {
      def[i].push(idxObj);
     }
    }
   }
  }
  else
  {
   if (isNaN(obj[i]) || i.indexOf('_key') > -1){
    def[i] = obj[i];
   }
   else{
    def[i] += obj[i];
   }
  }
 }
 return def;
}

例如有以下两个对象:

var data1 = {
 "_id" : "577327c544bd90be508b46cc",
 "channelId_info" : [
 {
  "channelId_key" : "0",
  "secondLevel_group" : [
  {
   "secondLevel_key" : "568cc36c44bd90625a045c60",
   "sender_group" : [
   {
    "sender_key" : "577327c544bd90be508b46cd",
    "sender_sum" : 40.0
   }
   ],
   "senders_sum" : 40.0
  }
  ],
  "channelId_sum" : 40.0
 }
 ],
 "car_sum" : 40.0
};

var data2 = {
 "_id" : "577327c544bd90be508b46cc",
 "channelId_info" : [
 {
  "channelId_key" : "0",
  "secondLevel_group" : [
  {
   "secondLevel_key" : "568cc36c44bd90625a045c60",
   "sender_group" : [
   {
    "sender_key" : "577327c544bd90be508b46cd",
    "sender_sum" : 20.0
   },
   {
    "sender_key" : "5710bcc7e66620fd4bc0914f",
    "sender_sum" : 5.0
   }
   ],
   "senders_sum" : 25.0
  },
  {
   "secondLevel_key" : "55fbeb4744bd9090708b4567",
   "sender_group" : [
   {
    "sender_key" : "5670f993a2f5dbf12e73b763",
    "sender_sum" : 10.0
   }
   ],
   "senders_sum" : 10.0
  }
  ],
  "channelId_sum" : 35.0
 },
 {
  "channelId_key" : "1",
  "secondLevel_group" : [
  {
   "secondLevel_key" : "568cc36c44bd90625a045c60",
   "sender_group" : [
   {
    "sender_key" : "577327c544bd90be508b46cd",
    "sender_sum" : 20.0
   }
   ],
   "senders_sum" : 20.0
  }
  ],
  "channelId_sum" : 20.0
 }
 ],
 "car_sum" : 55.0
};

合并之后的结果如下:

{
 "_id": "577327c544bd90be508b46cc",
 "channelId_info": [
  {
   "channelId_key": "0",
   "secondLevel_group": [
    {
     "secondLevel_key": "568cc36c44bd90625a045c60",
     "sender_group": [
      {
       "sender_key": "577327c544bd90be508b46cd",
       "sender_sum": 60
      },
      {
       "sender_key": "5710bcc7e66620fd4bc0914f",
       "sender_sum": 5
      }
     ],
     "senders_sum": 65
    },
    {
     "secondLevel_key": "55fbeb4744bd9090708b4567",
     "sender_group": [
      {
       "sender_key": "5670f993a2f5dbf12e73b763",
       "sender_sum": 10
      }
     ],
     "senders_sum": 10
    }
   ],
   "channelId_sum": 75
  },
  {
   "channelId_key": "1",
   "secondLevel_group": [
    {
     "secondLevel_key": "568cc36c44bd90625a045c60",
     "sender_group": [
      {
       "sender_key": "577327c544bd90be508b46cd",
       "sender_sum": 20
      }
     ],
     "senders_sum": 20
    }
   ],
   "channelId_sum": 20
  }
 ],
 "car_sum": 95
}

总结

以上就是这篇文章的全部内容了,文中提到的上述代码在日常工作中很有用,值得大家收藏!希望本文的内容对大家的学习或者工作能带来一定的帮助。

Javascript 相关文章推荐
dojo 之基础篇(三)之向服务器发送数据
Mar 24 Javascript
学习ExtJS fit布局使用说明
Oct 08 Javascript
Javascript 二维数组
Nov 26 Javascript
JavaScript极简入门教程(三):数组
Oct 25 Javascript
实例讲解使用原生JavaScript处理AJAX请求的方法
May 10 Javascript
jquery自适应布局的简单实例
May 28 Javascript
基于JavaScript实现树形下拉框
Aug 10 Javascript
SpringMVC+bootstrap table实例详解
Jun 02 Javascript
jQuery回调方法使用示例
Jun 26 jQuery
javascript自定义事件功能与用法实例分析
Nov 08 Javascript
为jquery的ajax请求添加超时timeout时间的操作方法
Sep 04 jQuery
Vue.js的动态组件模板的实现
Nov 26 Javascript
javascript 闭包详解及简单实例应用
Dec 31 #Javascript
深入理解Angularjs中的$resource服务
Dec 31 #Javascript
BootStrap Fileinput的使用教程
Dec 30 #Javascript
BootStrap Fileinput初始化时的一些参数
Dec 30 #Javascript
bootstrapValidator表单验证插件学习
Dec 30 #Javascript
JS实现类似百叶窗下拉菜单效果
Dec 30 #Javascript
BootStrap实现轮播图效果(收藏)
Dec 30 #Javascript
You might like
人族 TERRAN 概述
2020/03/14 星际争霸
PHP中auto_prepend_file与auto_append_file用法实例分析
2014/09/22 PHP
常用js脚本
2006/12/03 Javascript
深入理解JavaScript 闭包究竟是什么
2013/04/12 Javascript
基于jQuery.Validate验证库知识点的详解
2013/04/26 Javascript
深入理解JavaScript系列(28):设计模式之工厂模式详解
2015/03/03 Javascript
jQuery关键词说明插件cluetip使用指南
2015/04/21 Javascript
js实现当前输入框高亮显示的方法
2015/08/19 Javascript
javascript如何写热点图
2015/12/08 Javascript
基于javascript简单实现对身份证校验
2021/01/25 Javascript
Bootstrap3学习笔记(二)之排版
2016/05/20 Javascript
JS焦点图,JS 多个页面放多个焦点图的实例
2016/12/08 Javascript
Ionic项目中Native Camera的使用方法
2017/06/07 Javascript
vue-router路由与页面间导航实例解析
2017/11/07 Javascript
详解将微信小程序接口Promise化并使用async函数
2019/08/05 Javascript
微信小程序之数据绑定原理解析
2019/08/14 Javascript
JS中比Switch...Case更优雅的多条件判断写法
2019/09/05 Javascript
Python中的迭代器漫谈
2015/02/03 Python
Python基于回溯法子集树模板解决旅行商问题(TSP)实例
2017/09/05 Python
python并发2之使用asyncio处理并发
2017/12/21 Python
python写入并获取剪切板内容的实例
2018/05/31 Python
详解Numpy中的广播原则/机制
2018/09/20 Python
OpenCV搞定腾讯滑块验证码的实现代码
2019/05/18 Python
python操作文件的参数整理
2019/06/11 Python
python 字典有序并写入json文件过程解析
2019/09/30 Python
离线状态下在jupyter notebook中使用plotly实例
2020/04/24 Python
基于python实现坦克大战游戏
2020/10/27 Python
详解HTML5中的Communication API基本使用方法
2016/01/29 HTML / CSS
摩托车和ATV零件、配件和服装的首选在线零售商:MotoSport
2017/12/22 全球购物
英国性能汽车零件和发动机配件在线:Maxpeedingrods
2019/11/05 全球购物
初中女生自我鉴定
2013/12/19 职场文书
护理专业优质毕业生自荐书
2014/01/31 职场文书
优秀乡村医生事迹材料
2014/05/28 职场文书
设计师求职信
2014/07/01 职场文书
整改通知书格式
2015/04/22 职场文书
Python 多线程处理任务实例
2021/11/07 Python