Add two Name Pair Values to set value to a Name pair type field

RC19
Tera Contributor

I have below values

a = {"name1":"value1", "name2":"value2"}

b={"name3":"value3"}

 

and i need to get result added as below:

c= {"name1":"value1", "name2":"value2","name3":"value3"}

 

To set value into a Name-Value Pair type field . Please suggest a script with best practice .

6 REPLIES 6

-O-
Kilo Patron
Kilo Patron

The fields return a JSON when read.

So to achieve what you want, one needs to

  • read the value,
  • turn it into an object (using JSON.parse),
  • add the new key-value pair,
  • turn the object into a JSON and
  • set the value to the JSON obtained.

Something like this should work:

// Read the value
var valueJSON = g_form.getValue('<field name>'),
    // Turn the value into an object
    value = JSON.parse(valueJSON);

// Add the new key-value pair
value['name3'] = 'value3';

// Turn the object into a JSON
valueJSON = JSON.stringify(value);

// Set/write the value obtained
g_form.setValue('<field name>', valueJSON);

The exact same thing would work server side, replacing g_form with a GlideRecord.

Community Alums
Not applicable

If you want to keep the properties of object a and object b, but have them merged into a new one you could try the following syntax:

 

var a = {"name1":"value1", "name2":"value2"};

var b = {"name3":"value3"};

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

 

if you dont need to keep the values - even easier:

 

var c = Object.assign(a,b)

 

Now if you need to assign this as a value to a record, it depends from where you are going to do it - client side or server side. I suspect it's from server side (makes more sense to me). So using the mentioned above or other approach, you need to split the object and use this approach:

for(var i in c){ // this is your merged object
    current.<your key-value field name here>[i] = c[i]; //this way you should iterate thru all keys and assign the values

}

With the important note that Object.assign is not available globally server side - perhaps in scopes when using 2021 compatibility mode.

You would need to use Object.extend instead.