简体   繁体   中英

nodejs execute string variable

I'm using sails.js. 1) I'd like to print 'dolphin' from object matchingCol.

var matchingCol = {
    'card': {
        'add': {
            'voo': 'dolphin'
        }
    }
};

module.exports = {

    methodA: function (req, res) {
        var a = 'card';
        var b = 'add';
        var c = 'voo';
        return res.send(matchingCol.a.b.c);
    },
};

2) If I'd like to declare object, and want to parse 'foo' to key, how can I do?

var key = 'foo';
var params = {
    key: 'anything'
};

Please help.

In JavaScript, if you have a variable that represents the property name of an object, you can use square brackets to access it:

 return res.send(matchingCol[a][b][c]);

You can also use square brackets for assignment:

 var key = 'foo';
 var params = {};
 params[key] = 'anything';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM