简体   繁体   中英

How can I get the keys of a node.js hash from a C++ module?

I have a C++ module that's being called from node.js. I would like to pass in a hash and retrieve both the keys and values from the C++ code but I cannot figure out how to get them. Here's what I would like to handle:

var mod = require('MyModule')
var conn = mod.createConnection()
conn.connect( { 'uid': 'graeme',
                'pwd': 'mypassword' } )

Inside my C++ method, I can use args[0]->IsObject() to determine that the parameter is a hash, but I can't find a way to get the keys ('uid', 'pwd') or the values ('graeme', 'mypassword') from it.

Is there a way to get the keys and values from these kinds of objects?

Your second example of passing in an array doesn't really make sense, but to your general point, you can use GetOwnPropertyNames to read the names of properties.

Local<Object> obj = args[0].As<Object>();
Local<Array> props = obj->GetOwnPropertyNames();

for (int i = 0, len = props->Length(); i < len; i++){
    Local<String> key = props->Get(i).As<String>();
    Local<Value> val = obj->Get(key);
}

equivalent to:

var props = Object.getOwnPropertyNames(arguments[0]);
for (var i = 0, len = props.length; i < len; i++){
    var key = props[i];
    var value = arguments[0][key];
}

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