Dev
Dev

Reputation: 687

Node.js iterate over Object key's keys

Ok so I know the title is a lil confusing (maybe a lot) so let me explain. In an Object variable like a mongoose schema there can be types as String, Number, Boolean, etc... But what if the type is a new Object? And what if that Object has another Object inside?

Let's say I got this schema in here:

user: {
    username: 'bob1',
    password: '1234',
    email: '[email protected]',
    profile: {
        name: {
            first: 'Bob',
            last: 'Marley'
        },
        gender: 'male',
        country: 'US'
    },
    userKeys: {
        username: { show: true },
        password: { show: false },
        email: { show: 'maybe' },
        profile: {
            name: {
                first: { show: true },
                last: { show: true }
            },
            gender: { show: false },
            country: { show: 'maybe' }
        }
    }
}

and I want to create a new temporary Object in my file based on that user's userKeys returning only the values from the schema that have the value true or 'maybe' from the userKeys fields. How can I do that by iterating not only the keys from the basic structure but the keys inside the Object that is inside another Object? I have tried to do it with

Object.keys(user.userKeys).forEach((key) => {
    const cur = user[key];
    if (typeof cur === Object) {
        Object.keys(user.userKeys[key]).forEach((ok) => {
            console.log(ok, user.userKeys[ok].show);
            myObj.push(cur);
        });
    }
});

but it won't log anything that is a part of an Object (example: profile.name or profile.country).

I appreciate any tips.

Have a nice day

Upvotes: 0

Views: 2935

Answers (1)

Mark
Mark

Reputation: 92450

You can make a simple function that takes an object and looks at each key to see if there is a show: true or maybe adding each one to an array. Then for each object you look at, you recursively pass that back into the function. This makes a very succinct solution:

let object = {user: {username: 'bob1',password: '1234',email: '[email protected]',profile: {name: {first: 'Bob',last: 'Marley'},gender: 'male',country: 'US'},userKeys: {username: { show: true },password: { show: false },email: { show: 'maybe' },profile: {name: {first: { show: true },last: { show: true }},gender: { show: false },country: { show: 'maybe' }}}}}

function getTrueKeys(obj, res = []) {
    Object.keys(obj).forEach(k => {
        if (obj[k].show && (obj[k].show === true || obj[k].show === 'maybe')) res.push(k)
        if (typeof obj[k] === 'object') getTrueKeys(obj[k], res)
    })
    return res
}

console.log(getTrueKeys(object.user.userKeys))

Upvotes: 1

Related Questions