0

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.

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
  • 1
    params help - https://youtu.be/jbtjGii300k – sikka karma Apr 18 '20 at 10:30
  • @sikkakarma - thankyou for that. I previously thought that the params argument was specific to ClearScript but now I appreciate it is a standard C# mechanism for handling an unknown quantity of parameters. – Vanquished Wombat Apr 18 '20 at 10:44

1 Answers1

2

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.

BitCortex
  • 3,328
  • 1
  • 15
  • 19
  • 1
    The ScriptObject documentation (linked above) explains how to access script object data. You can transform that data into a dictionary or some other data structure as your application requires. Script objects are mostly just property bags, so your suggestion would certainly work, but you'll have to decide whether it'll work for your purposes. Note that script objects can have indexed properties in addition to named properties, so you may need to incorporate those into your dictionary as well. – BitCortex Apr 20 '20 at 14:26
  • 1
    Sorry, I didn't intend to respond in an RTFM fashion. I'll update my answer. – BitCortex Apr 20 '20 at 15:07
  • Thanks @BitCortex - I still have more to learn but you have answered my question including adding something useful for future readers. Have accepted your answer. – Vanquished Wombat Apr 20 '20 at 15:27