百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 详解Node.js中如何合并两个复杂对象
分享文章到:

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

发布时间:01/15 来源: 浏览: 关键词:
小编推荐的这篇文章详细解析了Node.js中如何合并两个复杂对象的教程,有兴趣的同学可以参考一下

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

Node.js合并两个复杂对象

例如我有以下两个object:

 
 代码如下
varobj1 = {
 "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
 }
 ]
};
 
varobj2 = {
 "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现有的方法我们无法实现上述结果,那只能自己写代码来实现了。

 
 代码如下
functionmergeObjs(def, obj) {
 if(!obj) {
 returndef;
 }elseif(!def) {
 returnobj;
 }
 
 for(variinobj) {
 // 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.
 elseif(obj[i] !=null&& (obj[i]instanceofArray) && 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)
  {
  varnewobjs = [];
  // 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.
  varobjids = {}
  for(varx= 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(varx= 0, l= obj[i].length; x < l; x++)
  {
   varnewobj = obj[i][x];
   if(objids[newobj.id] !== undefined)
   {
   def[i][x] = mergeObjs(def[i][x],newobj);
   }
   else{
   newobjs.push(newobj);
   }
  }
 
  for(varx= 0, l = newobjs.length; x<l; x++) {
   def[i].push(newobjs[x]);
  }
  }
  else{
  for(varx=0; x < obj[i].length; x++)
  {
   varidxObj = obj[i][x];
   if(def[i].indexOf(idxObj) === -1) {
    def[i].push(idxObj);
   }
  }
  }
 }
 else
 {
  def[i] = obj[i];
 }
 }
 returndef;}
 

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

 
 代码如下
functionmerge(def, obj) {
 if(!obj) {
  returndef;
 }
 elseif(!def) {
  returnobj;
 }
 
 for(variinobj) {
  // 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.
  elseif(obj[i] !=null&& (obj[i]instanceofArray) && 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)
   {
    varnewobjs = [];
    // 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.
    varobjids = {}
    for(varx= 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(varx= 0, l= obj[i].length; x < l; x++)
    {
     varnewobj = obj[i][x];
     if(objids[newobj.id] !== undefined)
     {
      def[i][x] = merge(def[i][x],newobj);
     }
     else{
      newobjs.push(newobj);
     }
    }
 
    for(varx= 0, l = newobjs.length; x<l; x++) {
     def[i].push(newobjs[x]);
    }
   }
   else{
    for(varx=0; x < obj[i].length; x++)
    {
     varidxObj = 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];
   }
  }
 }
 returndef;
}
 

例如有以下两个对象:

 
 代码如下
vardata1 = {
 "_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
};
 
vardata2 = {
 "_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
}
 
打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有4人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板