Navigate object using string?

Viewed 14

What I want to do is a function to convert a string to a "path" to find something in an object

For example:

let users = [
    {
        email: "person1@example.com",
        data: {
            userID: "1",
        },
    },
    {
        email: "person2@example.com",
        data: {
            userID: "2",
        },
    },
];

let queryString = "data.userID"
let valueToFind = "1"

let query = queryString.split(".")
let user = users.find(user => user[query[0]][query[1]] == valueToFind)

But, I want to do this [query[number]] for as many times as there are . in the queryString, something like mongoose search, for objects.

Which work something like this:

User.findOne({ 'data.userID': "1" });

Is there any way to do this? Thanks in advance.

0 Answers
Related