Join Objects | object.assign() does not work

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

var c = Object.assign(a, b);
gs.log(c);

 

why ;)?

1 ACCEPTED SOLUTION

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

5 REPLIES 5

Paul Hegel
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).