[英]How do I iterate over properties in an Object
I want to iterate through an Object in a V8 C++ function. 我想遍历V8 C ++函数中的对象。
NodeJS: 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: 我想将名称和值的“用户”和“密码”传递给采用如下参数的C ++方法:
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 :) 我一直在为Node&V8编写更简单的C ++包装器,但是我对此用尽了很多想法:)
Assuming recent enough v8 (io.js or node 0.12), where the_object
is the object passed from js 假设最近有足够的v8(io.js或节点0.12),其中
the_object
是从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
}
}
Since I just did this for my gem I might add some subtle changes to this answer by @Esailija which is now deprecated: 因为我只是为我的宝石做的,所以我可能会对@Esailija的答案进行一些微妙的更改,现在已弃用:
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 主要的补充是
This works now, but as always be sure to check v8.h
to get the latest non deprecated way. 现在可以使用,但是一如既往,请务必检查
v8.h
以获取最新的不推荐使用的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.