- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-16-2021 04:54 AM
var a = {
"a": "1",
"b": "2"
};
var b = {
"c": "1",
"d": "2"
};
var c = Object.assign(a, b);
gs.log(c);
why ;)?
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-16-2021 05:17 AM
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;
}

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-16-2023 04:57 PM
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).