Ankur Bawiskar
Tera Patron

Hi,

you can use this sample script to merge

var a = {
    "a": "1",
    "b": "2"
};
var b = {
    "c": "1",
    "d": "2"
};

var arr = [];
arr.push(a);
arr.push(b);

gs.info(JSON.stringify(arr));

Regards
Ankur

@Meloper 

Do you require to merge those 2 objects?

then using array would be easier.

Regards
Ankur

Upender Kumar
Mega Sage

Try below

 

var a = {
			"a": "1",
			"b": "2"
		};
		var b = {
			"c": "1",
			"d": "2"
		};

		
gs.print(JSON.stringify(merge(a,b)))
		function merge(from,to){
			for (var name in from){
				var mached=false;
				for(var dt in to){
					if(dt==name)
						mached=true;
				}
				if(!mached)
					to[name]=from[name];

			}
return to;
			
		}

View solution in original post

ReginaldoC
Tera Contributor

I believe the answers are just trying to circumvent a BUG!

The point is Object.assign should work on ServiceNow since it is a standard javascript prototype function.

phegel
Mega Guru

I had problems with the solution, so did some research and found a way to replicate what Object.assign(target, source) function does:

function	objectAssign (target, source){ 
		Object.keys(source).forEach(function(key, index) {
			// key: the name of the object key
			gs.info(key + ': ' + source[key]);  // just so you can see what's happening...
			target[key] = source[key];
		});
		return target;

	}
	function test(target){
		  var source = { a: 1, b: 1, c: 1 };
		  var retVal = objectAssign(target, source);
		  return retVal;
	}
	var target = {};
	var rv = test(target);
	gs.info('target: ' + global.JSON.stringify(target)); // result: target: {"a":1,"b":1,"c":1}  - use this value to modify an inbound parameter.
	gs.info('rv: ' + global.JSON.stringify(rv)); // result: rv: {"a":1,"b":1,"c":1} -- this is a new object and is not the target reference.

The objectAssign function does a shallow assign of the top level properties to the inbound target from the source. Does by Reference copy, so the target is modified. Do not assign the object if you want to continue using by reference.  It works the same as Object.assign(target, source) in ES6(which is not supported as noted in this post).