Sparlarva
Sparlarva

Reputation: 804

Get an objects value by accessing and matching it's key value

I am retrieving an object with a database call, I want to access a key's value by matching that key with a variable that I have.

In my database return I get an object that looks similar to this:

{"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"}

I have a variable:

var intent = 'emailAddress'

The variable should always exist but theres a very slight chance it may not and it may also be null.

What I want to do is access the value from that key field that matches the var intent, or at least get the key value pair.

What I also want to do is then if it is null then call an error, my full code is below:

getClientsDialog: function (domain, intent, callback) {

    MongoClient.connect('mongodb://111011001101101', function (err, client) {
        if (err) throw err;
        var db = client.db('10001101');
        db.collection('dialog').findOne({ domain: domain}, function (err, doc) {

    // here I would want to say if (!err && ****logic to check match****)
            if (!err) {

                callback(doc)
            } else {
                throw err;
                callback(err)
            }
            client.close();
        });
        console.dir("Called findOne");
    });

}

Any help would be greatly appreciated!

Thanks!!

Upvotes: 0

Views: 37

Answers (1)

Geraldo Megale
Geraldo Megale

Reputation: 363

Not sure if i got the problem right but in ES6 you can use a computed value as an property name. Something like this:

let serverJson = {
    "_id":"5c840d548a7db8af2f9eefea",
    "domain":"chatbotdemo.com","deliveryTime":"ba",
    "emailAddress":"ab","freeDelivery":"ab","onSale":"ab"
};

let intent = "emailAddress";

if (serverJson[intent]!== undefined)  {

}
else {

}

Upvotes: 1

Related Questions