Skip to content
Advertisement

Iterate through all children and children children of an object

I have an object with children objects, and even great grandchildren objects.

I am currently using

for (const [key, value] of Object.entries(myObj)) {
  console.log(`${key}: ${value}`);
}

Which produces, for example:

  • created_at: 2021-01-01T00:00:00.000Z
  • id: string
  • data: [object Object]
  • items: [object Object],[object Object]

How do I iterate through any number of child objects to return something similar to

  • created_at: 2021-01-01T00:00:00.000Z
  • id: string
  • data: [object Object]
  • data: 1 of 1 {contents}
  • items: 1 of 2 {contents}
  • items: 2 of 2 {contents}

The “1 of 2” isn’t needed, but demonstrates my output goal.

Advertisement

Answer

This is a situation where recursion is useful. For example:

function visitDescendants(obj, callback) {
    for (const [key, value] of Object.entries(obj)) {
        if (value && typeof value === "object") {
            // Recurse
            visitDescendants(value, callback);
        } else {
            callback(key, value);
        }
    }    
}

Live example:

function visitDescendants(obj, callback) {
    for (const [key, value] of Object.entries(obj)) {
        if (value && typeof value === "object") {
            // Recurse
            visitDescendants(value, callback);
        } else {
            callback(key, value);
        }
    }    
}

const obj = {
    a: 1,
    message: "hi",
    b: {
        nestedMessage: "there",
        c: {
            furtherNestedMessage: "folks!"
        },
    },
};

visitDescendants(obj, (key, value) => {
    console.log(`${key}: ${value}`);
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement