The CreatorCon Call for Content is officially open! Get started here.

Please suggest how to convert object to array in javascript

Ketan Pandey
Tera Expert

Please suggest how to convert object to array in javascript

5 REPLIES 5

Jaspal Singh
Mega Patron
Mega Patron


Hi Ketan,

Seems a very generic ask. Did you check for some links already? If not, link1  link2

Samaksh Wani
Giga Sage

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

Harish Bainsla
Kilo Patron
Kilo Patron

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]

Ankur Bawiskar
Tera Patron
Tera Patron

@Ketan Pandey 

what script are you using and what's the use-case?

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader