How to Push Array Values into JSON Object

Vidya Lakshmi
Kilo Sage
Kilo Sage

Hi Team,

Im getting into a huge trouble here, Any help please on resolving this?

var obj = {};
obj.prop1 = {}; 
obj.prop2 = "Test"; 
obj.prop1.requested_for ="Roger Federer";
obj.prop1.Catalog_item = "Get me a Tennis racquet"; 
var json = JSON.stringify(obj); 
gs.print("Constructed JSON-----"+json);

This Simple Scripts works fine incase of the pushing the data normally and the result would be as below
Constructed JSON-----{"prop1":{"requested_for":"Roger Federer","Catalog_item":"Get me a Tennis racquet"},"prop2":"Test"}
But i have an issue where my requirement is,
var obj = {};
obj.prop1 = {}; 
obj.prop2 = "Test"; 
var Arr1 = ["x1","x2"];
var Arr2 = ["y1","y2"];
for(var i=0;i<Arr1.length;i++)
{
obj.prop1.Arr1[i]=Arr2[i]; // Something like this it has to be , the Object value has to be dynamic.
}
var json = JSON.stringify(obj); 
gs.print("Constructed JSON-----"+json);

The Output for the above has to be like below, which am not understanding on how to build the logic.
Constructed JSON-----{"prop1":{"x1":"y1","x2":"y2"},"prop2":"Test"}

Can anyone please help me with the above pleaseee
Thanks in advance !
 
 
 
1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Vidya,

try this script and it should work; i tried in background script;

I assume both the array at any point of time would have same number of values

var obj = {};

var Arr1 = ["x1","x2"];
var Arr2 = ["y1","y2"];
var obj1 = {};
for(var i=0;i<Arr1.length;i++)
{
obj1[Arr1[i]] = Arr2[i].toString();
}

obj.prop1 = obj1; 
obj.prop2 = "Test"; 

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

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

2 REPLIES 2

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Vidya,

try this script and it should work; i tried in background script;

I assume both the array at any point of time would have same number of values

var obj = {};

var Arr1 = ["x1","x2"];
var Arr2 = ["y1","y2"];
var obj1 = {};
for(var i=0;i<Arr1.length;i++)
{
obj1[Arr1[i]] = Arr2[i].toString();
}

obj.prop1 = obj1; 
obj.prop2 = "Test"; 

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

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Thanks a lot for this.

This saved my work.

Many thanks !