3

I want to iterate through an Object in a V8 C++ function.

NodeJS:

node.addProperties({"user":"testuser","password":"passwd"};

I want to pass "user" and "password", both names and values to a C++ method which takes parameters like:

AddProperty(char * name, char * value);

The number of name/value pairs may differ, so I need a generic solution.

Could I get some help to be put on the right track.

I have been writing simpler C++ wrappers for Node & V8, but I am just running out of ideas for this one :)

Andreas Selenwall
  • 5,705
  • 11
  • 45
  • 58

2 Answers2

6

Assuming recent enough v8 (io.js or node 0.12), where the_object is the object passed from js

Local<Array> property_names = the_object->GetOwnPropertyNames();

for (int i = 0; i < property_names->Length(); ++i) {
    Local<Value> key = property_names->Get(i);
    Local<Value> value = the_object->Get(key);

    if (key->IsString() && value->IsString()) {
        String::Utf8Value utf8_key(key);
        String::Utf8Value utf8_value(value);
        AddProperty(*utf8_key, *utf8_value);
    } else {
        // Throw an error or something
    }
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
4

Since I just did this for my gem I might add some subtle changes to this answer by @Esailija which is now deprecated:

if (value->IsObject()) {
    Local<Context> context = Context::New(isolate);
    Local<Object> object = value->ToObject();
    MaybeLocal<Array> maybe_props = object->GetOwnPropertyNames(context);
    if (!maybe_props.IsEmpty()) {
        Local<Array> props = maybe_props.ToLocalChecked();
        for(uint32_t i=0; i < props->Length(); i++) {
           Local<Value> key = props->Get(i);
           Local<Value> value = object->Get(key);
           // do stuff with key / value
        }
    }

 }

The main addition is that

  • You got to have a context going to get property names, the old way is getting deprecated
  • You need to be careful when converting the value to an object

This works now, but as always be sure to check v8.h to get the latest non deprecated way.

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506