Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Java Map to a basic Javascript object?

I'm starting to use the dynamic rhinoscript feature in Java 6 for use by customers who are more likely to know Javascript than Java.

What is the best way to pass a Map (associative array, javascript obj, whatever) into Javascript so the script-writers can use the standard Javascript dot notation for accessing values?

I'm currently passing a java.util.Map of values into the script, however then the script writer has to write "map.get('mykey')" instead of "map.mykey".

Basically, I want to do the opposite of this question.

like image 369
Jon Carlson Avatar asked Sep 22 '11 18:09

Jon Carlson


People also ask

How do you turn a Map into an object?

To convert a Map to an object, call the Object. fromEntries() method passing it the Map as a parameter, e.g. const obj = Object. fromEntries(map) . The Object.

Can we use Map on objects in JavaScript?

A Map is an iterable, so it can be directly iterated. Object does not implement an iteration protocol, and so objects are not directly iterable using the JavaScript for...of statement (by default). Note: An object can implement the iteration protocol, or you can get an iterable for an object using Object.


1 Answers

I took the Java NativeObject approach and here is what I did...

// build a Map
Map<String, String> map = new HashMap<String, String>();
map.put("bye", "now");

// Convert it to a NativeObject (yes, this could have been done directly)
NativeObject nobj = new NativeObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
    nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
}

// Get Engine and place native object into the context
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
engine.put("map", nobj);

// Standard Javascript dot notation prints 'now' (as it should!)
engine.eval("println(map.bye);");
like image 160
Jon Carlson Avatar answered Sep 18 '22 16:09

Jon Carlson