We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

Getting the value and length of an array in JSON format

k_47
Tera Contributor

I would like to get the length and value of the following array in Client Script.

 

[{"key1": "a", "key2": "c", "key3": "e"}
,{"key1": "b", "key2": "d", "key3": "f"}]

 

*a-f contain sys_id.

 

The results I want are as follows
Length: 2 (for {}*2)
Value: a-f

 

This array is from getting the value of Multi Rows in variable set.

 

I tried using foreach, JSON.stringify, JSON.parse, etc,
I could not get the value, perhaps I am using them incorrectly.

Is it not possible to use it for [{}]type arrays?

 

If you know anything about this, please let me know.

Best Regards

1 ACCEPTED SOLUTION

Vishal Birajdar
Giga Sage

Hello @k_47 

 

Can you try below logic...

I have tried it in background script...you can try once...

 

/*1.Assuming this is data we get */
var payload = [{"key1": "a", "key2": "c", "key3": "e"}
,{"key1": "b", "key2": "d", "key3": "f"}];

/*2.Print length of payload array */
gs.print(payload.length);

/*3.Decalre array */
var myKeysValues =[];

/*4. Loop through payload array */
for(var i=0; i<payload.length ;i++){
    /*4.1 Here we will get array of kays for objects in payload array */
    var getKeys = Object.keys(payload[i])
     /*4.2 Loop through getKeys array */
     for(var j=0; j<getKeys.length;j++){
        /*4.3 Push values of keys in myKeusValues array */
        myKeysValues.push(payload[i][getKeys[j]]);
    
     }
}

gs.print(myKeysValues);









 

 

VishalBirajdar_0-1706532461618.png

 

 

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

View solution in original post

5 REPLIES 5

@hamlin, can you share your issue? possibly code?