Print JSON objects values into an array

Lucky1
Tera Guru

Hello all,

 

Can someone help me with code?

 

Scenario:

There are three objects.

var obj = {a:3,b:9.c:5}

var obj1 = {g:12,h:27,I:4}

var obj2 = {x:15,y:10:z:7}

 

So, now I need to print all the values into an array in ascending order.

Can someone please help me in code how to achieve this?

 

 

Regards,

Lucky

6 REPLIES 6

Valmik Patil1
Kilo Sage

Hello @Lucky1 ,

You can use below script.

 

// Define the objects
var obj = { a: 3, b: 9, c: 5 };
var obj1 = { g: 12, h: 27, I: 4 };
var obj2 = { x: 15, y: 10, z: 7 };

// Initialize an empty array to store values
var values = [];

// Manually extract values from each object using a for...in loop
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    values.push(obj[key]);
  }
}

for (var key in obj1) {
  if (obj1.hasOwnProperty(key)) {
    values.push(obj1[key]);
  }
}

for (var key in obj2) {
  if (obj2.hasOwnProperty(key)) {
    values.push(obj2[key]);
  }
}

// Sort the values in ascending order
values.sort(function(a, b) {
  return a - b;  // For numeric sorting
});

// Log the sorted values to the Script Execution log
gs.print('Sorted Values: ' + values.join(', '));

 

Output : 

 

*** Script: Sorted Values: 3, 4, 5, 7, 9, 10, 12, 15, 27

 

try running it in background script

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

Thanks,

Valmik Patil

Hi Valmik,

 

I understand that hasOwnProperty gives true or false if the key is present in the object.

But can you explain me the line 

for (var key in obj)

What is this key in obj ??

 

Thank you

 

 

Lucky 

Hello @Lucky1 ,

for (var key in obj) means : This helps to iterate over the object keys and values to fetch values.

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

Thanks,

Valmik Patil

 

shivatmika_19
Tera Guru

Hi @Lucky1

You can try this code below:

var obj = {a:3,b:9.c:5}

var obj1 = {g:12,h:27,i:4}

var obj2 = {x:15,y:10:z:7}

 

var objvalues = Object.values(obj);
var objvalues1 = Object.values(obj1);
var objvalues2 = Object.values(obj2);

var combinedvalues = [...objvalues, ...objvalues1, ...objvalues2];
combinedvalues.sort((a, b) => a - b);

console.log(combinedvalues);