The Object.entries() method in JavaScript can be used to convert an object to an array – but it doesn’t work recursively. So here’s a function to accomplish that.
I can’t think of a reason why you’d want to do this, but it came up while putting together an article on using Object.entries() – so here it is!
Recursive Function for Converting Objects to Arrays
I’ll let the comments do the talking as to what’s going on. The gist of it is that (for whatever reason) you want to convert an object, and any objects within it, to array/key pair values as output by Object.entries(). Arrays themselves will be left as-is.
//Demonstration object - a mess of nested objects and arrays var myObject = { colour: 'blue', number: 43, name: 'Fred', enabled: true, subArray: [0, 1, { height: 60 }], subObject: { foo: 'bar', anotherSubObject: { deep: 'dive', mood: { happy: false } } } }; //Function to convert objects containing nested objects and arrays to array pairs similar to Object.entries() function propertiesToArray(val) { //By default (val is not object or array, return the original value) var result = val; // If object passed the result is the return value of Object.entries() if (typeof val === 'object' && !Array.isArray(val)) { result = Object.entries(val); // If one of the results is an array or object, run this function on them again recursively result.forEach((attr) => { attr[1] = propertiesToArray(attr[1]); }); } //If array passed, run this function on each value in it recursively else if (Array.isArray(val)) { val.forEach((v, i, a) => { a[i] = propertiesToArray(v) }); } // Return the result return result; } // Test the function console.log(propertiesToArray(myObject));