Peter Fox Peter Fox - 2 years ago 63
Javascript Question

In Javascript what would be the simplest function to get the namespace of a multi depth object

Sorry if the title is a bit miss leading, I'll give an example of what I wish to do.

If I have a object say:

testable: {
some: {
id: 10
another: {
some: {
id: 20
an : {
arrayExample: ['test']

and I want an easy way to get an array of all the keys for non object values like so:

['','', '']

How would I do it? I assume I'd need a recursive function to build such an array as I'd have to do a for loop through each object and grab the key and add it to the previous namespace before pushing it into an array.

Also is this a bit to costly as a function? Especially if I'm going to use the array afterwards to grab the values.

Answer Source

You could use an iterative an recursive approach to get all keys of the object and array.

For all nested keys, you nedt to iterate over all items. There is no short circuit or other way around to skipt that task.

If you have some fancy names like 'item.0' you may get the wrong path to it.


Added a function getValue for getting a value from a path to a property/item. This works for falsey values as well.

function getPath(object) {
    function iter(o, p) {
        if (Array.isArray(o) ){
            o.forEach(function (a, i) {
                iter(a, p.concat(i));
        if (typeof o === 'object') {
            Object.keys(o).forEach(function (k) {
                iter(o[k], p.concat(k));

    var path = [];
    iter(object, []);
    return path;

function getValue(object, path) {
    return path.split('.').reduce(function (r, a) {
        return (Array.isArray(r) || typeof r === 'object') ? r[a] : undefined;
    }, object);

var obj = { testable: { some: { id: 10, number: 0 }, another: { some: { id: 20 } }, an: { arrayExample: ['test'] } } },
    path = getPath(obj);

document.write('<pre>' + JSON.stringify(getPath(obj), 0, 4) + '</pre>');
path.forEach(function (a) {
    document.write(getValue(obj, a) + '<br>');

//path.forEach(function (a) {
//    console.log(getValue(obj, a));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download