- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-16-2021 04:59 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-16-2021 11:23 PM
Do you require to merge those 2 objects?
then using array would be easier.
Regards
Ankur
- 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-05-2022 06:37 AM
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.
- 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).