Please suggest how to convert object to array in javascript
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-29-2023 10:09 PM
Please suggest how to convert object to array in javascript

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-29-2023 10:15 PM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-29-2023 10:16 PM
Hello @Ketan Pandey
This example converts a Java object to an array.
var arrayUtil = new ArrayUtil(); // Returns a JavaObject with the logged in user's groups var groupObj = gs.getUser().getMyGroups(); gs.print('groupObj: ' + Object.prototype.toString.call(groupObj)); var groupArr = arrayUtil.convertArray(groupObj); gs.print('groupArr: ' + Object.prototype.toString.call(groupArr));
Output
groupObj: [object JavaObject] groupArr: [object Array]
Plz mark my solution as Accept, If you find helpful.
Regards,
Samaksh
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-29-2023 11:17 PM
To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use Object.keys() , Object.values() , or Object.entries() . To convert an async iterable to an array, use Array.fromAsync() . Array.from() never creates a sparse array.
Object Values Method:The Object.values() method returns an array containing the values of an object's properties in the same order as provided by a for...in loop.
const obj = { a: 1, b: 2, c: 3 };
const array = Object.values(obj);
console.log(array); // Output: [1, 2, 3]
Object Entries Method:
const obj = { a: 1, b: 2, c: 3 };
const array = Object.entries(obj);
console.log(array); // Output: [['a', 1], ['b', 2], ['c', 3]]
Manual Conversion:
const obj = { a: 1, b: 2, c: 3 };
const array = [];
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
array.push(obj[key]);
}
}
console.log(array); // Output: [1, 2, 3]
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-29-2023 11:38 PM
what script are you using and what's the use-case?
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader