Converting Object to an Array Recursively in JavaScript

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));

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment