How do can I convert to a dictionary of name & value pairs from a JS object passed into a host C# method ? My problem is how to interpret the 'object's that are received at the exec function. If they were int's I could just use...
foreach (int i in args)...
...but they are...what ?
For example, in a JS file I have
myApi.exec("doThang", { dog: "Rover", cat: "Purdy", mouse: "Mini", <non-specific list of more...> } );
In C# I have
public void foo()
{
var engine = new V8ScriptEngine();
engine.AddHostObject("myApi", a); // see below
// load the above JS
string script = loadScript();
// execute that script
engine.Execute(script);
}
public class a
{
public void exec(string name, params object[] args){
// - how to iterate the args and create say a dictionary of key value pairs?
}
}
EDIT: Changed the specifics of the question now that I understand the 'params' keyword is not specifically part of ClearScript.
You can use ScriptObject
. Script objects can have indexed properties as well as named properties, so you could create two dictionaries:
public void exec(string name, ScriptObject args) {
var namedProps = new Dictionary<string, object>();
foreach (var name in args.PropertyNames) {
namedProps.Add(name, args[name]);
}
var indexedProps = new Dictionary<int, object>();
foreach (var index in args.PropertyIndices) {
indexedProps.Add(index, args[index]);
}
Console.WriteLine(namedProps.Count);
Console.WriteLine(indexedProps.Count);
}
If you don't expect or care about indexed properties, you can skip indexedProps
. Or you could build a single Dictionary<object, object>
instance to hold both.