Search code examples
javascriptjavaarraysobjectnashorn

Java Nashorn equivalent of pushing object to array in Javascript


In Javascript I would like to iterate through something, create an object for each iteration, set some values, and push that to an array.

var arr = [];
data.forEach(function(d) {
    var obj = {};
    obj.id = d.id;
    obj.value = d.value;
    arr.push(obj);
 })

How do I accomplish this in Nashorn?

I have tried

var ArrayList = Java.type("java.util.ArrayList");
var list = new ArrayList();

 list.add(obj)  

type of approach though I am not getting the values back out?


Solution

  • I Dont think I fully understand the question but asuming you are refering to adding a javascript object to a Java ArrayList from Nashhorn you can do the following.

    jjs> var myList = Java.type('java.util.ArrayList');
    jjs> var list = new myList();
    jjs> list.add({a:1})
    true
    jjs> list.get(0).a
    1
    

    Hope it helps