Print JSON objects values into an array
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-03-2024 04:01 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-03-2024 09:56 PM
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:
"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
Juhi Poddar
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-03-2024 11:04 PM
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