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

Juhi Poddar
Kilo Patron

Hello @Lucky1 

To meet the requirement you can refer the script:

// Define 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 };

// Store all objects in an array
var objects = [obj, obj1, obj2];

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

// Iterate through each object and extract values
for (var i = 0; i < objects.length; i++) {
    var currentObj = objects[i];
    for (var key in currentObj) {
        if (currentObj.hasOwnProperty(key)) {
            allValues.push(currentObj[key]);
        }
    }
}

// Sort the array in ascending order
allValues.sort(function (a, b) {
    return a - b;
});

// Print the sorted array
gs.print(allValues);

Result: 

JuhiPoddar_0-1733291773353.png

 

"If you found my answer helpful, please like and mark it as an "accepted solution". It helps others find the solution more easily and supports the community!"

 

Thank You
Juhi Poddar

Chaitanya ILCR
Mega Patron

Hi @Lucky1 ,

Try this out

var obj = { a: 3, b: 9, c: 5 };
var obj1 = { g: 12, h: 27, I: 4 };
var obj2 = { x: 15, y: 10, z: 7 };
Object.assign(obj, obj1, obj2); // 
// gs.print(Object.values(obj).sort()) Object.values method doesn't support in ES5
var tempArr = [];
for (i in obj)
    tempArr.push(obj[i]);

gs.print(tempArr.sort(function(a, b) {
    return a - b;
}));

 

Regards,
Chaitanya