Node.js中如何合并对象具体用法代码实例详解
在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 }
以上是Node.js中如何合并对象具体用法代码实例详解的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

如何使用WebSocket和JavaScript实现在线语音识别系统引言:随着科技的不断发展,语音识别技术已经成为了人工智能领域的重要组成部分。而基于WebSocket和JavaScript实现的在线语音识别系统,具备了低延迟、实时性和跨平台的特点,成为了一种被广泛应用的解决方案。本文将介绍如何使用WebSocket和JavaScript来实现在线语音识别系

WebSocket与JavaScript:实现实时监控系统的关键技术引言:随着互联网技术的快速发展,实时监控系统在各个领域中得到了广泛的应用。而实现实时监控的关键技术之一就是WebSocket与JavaScript的结合使用。本文将介绍WebSocket与JavaScript在实时监控系统中的应用,并给出代码示例,详细解释其实现原理。一、WebSocket技

如何利用JavaScript和WebSocket实现实时在线点餐系统介绍:随着互联网的普及和技术的进步,越来越多的餐厅开始提供在线点餐服务。为了实现实时在线点餐系统,我们可以利用JavaScript和WebSocket技术。WebSocket是一种基于TCP协议的全双工通信协议,可以实现客户端与服务器的实时双向通信。在实时在线点餐系统中,当用户选择菜品并下单

如何使用WebSocket和JavaScript实现在线预约系统在当今数字化的时代,越来越多的业务和服务都需要提供在线预约功能。而实现一个高效、实时的在线预约系统是至关重要的。本文将介绍如何使用WebSocket和JavaScript来实现一个在线预约系统,并提供具体的代码示例。一、什么是WebSocketWebSocket是一种在单个TCP连接上进行全双工

JavaScript和WebSocket:打造高效的实时天气预报系统引言:如今,天气预报的准确性对于日常生活以及决策制定具有重要意义。随着技术的发展,我们可以通过实时获取天气数据来提供更准确可靠的天气预报。在本文中,我们将学习如何使用JavaScript和WebSocket技术,来构建一个高效的实时天气预报系统。本文将通过具体的代码示例来展示实现的过程。We

用法:在JavaScript中,insertBefore()方法用于在DOM树中插入一个新的节点。这个方法需要两个参数:要插入的新节点和参考节点(即新节点将要被插入的位置的节点)。

JavaScript教程:如何获取HTTP状态码,需要具体代码示例前言:在Web开发中,经常会涉及到与服务器进行数据交互的场景。在与服务器进行通信时,我们经常需要获取返回的HTTP状态码来判断操作是否成功,根据不同的状态码来进行相应的处理。本篇文章将教你如何使用JavaScript获取HTTP状态码,并提供一些实用的代码示例。使用XMLHttpRequest

JavaScript是一种广泛应用于Web开发的编程语言,而WebSocket则是一种用于实时通信的网络协议。结合二者的强大功能,我们可以打造一个高效的实时图像处理系统。本文将介绍如何利用JavaScript和WebSocket来实现这个系统,并提供具体的代码示例。首先,我们需要明确实时图像处理系统的需求和目标。假设我们有一个摄像头设备,可以采集实时的图像数
