0

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: 'someone@example.com',
    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

Dev
  • 677
  • 1
  • 8
  • 19
  • Recursion. See [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/q/11922383/218196) – Felix Kling Jun 26 '18 at 17:24

1 Answers1

1

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: 'someone@example.com',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))
Mark
  • 90,562
  • 7
  • 108
  • 148