Java and JavaScript - Utilizing a Map

I'm currently using Rhino to run JavaScript code within my Java program, but I've encountered a problem with iterating over the map in JavaScript.

On the Java side:

private final Map<Long, ClassEmployees > employees ;
...
employees.put (numEmployees, new ClassEmployees());
...

On the JavaScript side:

keys = employees.keySet();
for (var i in keys) {
  print ("++ " + i);   // ===> why is this printing methods?
}

Output :

++ getClass
++ iterator
++ toArray
++ addAll
++ remove
++ equals
++ containsAll
++ class
++ hashCode
++ contains
++ wait
++ add
++ size
++ clear
++ isEmpty
++ notify
++ empty
++ retainAll
++ toString
++ notifyAll
++ removeAll

Answer №1

In Java, the variable keys is pointing to a Set object. However, when using JavaScript's for in loop, it doesn't know how to handle iterating over this type of object and instead treats it as a regular object.

The for...in loop in JavaScript loops through the enumerable properties of an object.

Since the methods of a Set object are considered enumerable properties, that's what you'll end up iterating over.

If you want to iterate through the actual values stored in your Set, you should use an explicit iterator like in Java or convert it to an array first:

for each (var i in keys.toArray()) {
     //...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Navbar values in a React application be dynamically updated depending on the user's login status?

As someone new to React, I am exploring the correct approach to building a Navbar that dynamically displays different links based on a user's login status. When a user logs in, a cookie loggedIn=true is set. In my Navbar component, I utilize window.se ...

Ways to reference an Array variable using a string in JavaScript

const EleList = [1,2,3] name = 'Ele' const render = function(type){ window[type + 'List'].forEach(function(value){ console.log("LOL") }); render('Ele') I'm trying to dynamically call an array using a string. Wh ...

Log4j Vulnerability: Strategies for addressing the security flaw in Log4j without upgrading to version 2.15.0

Currently, I am utilizing Log4j 1.2.16 within a Maven project that involves Selenium testing in Java. My goal is to find a solution that does not involve upgrading the version of Log4j. <dependency> <groupId>log4j</groupId> < ...

Implementing multiple filters for object arrays in Angular 8

On my current project, I am interested in implementing multiple filters. The filters I want to use include price range, type, and uploaded date. For uploaded date, I have a checkbox with options for Today, Last 2 days, Last 7 days, and Any. When it come ...

Steps for running example of JavaScript colormap:

After discovering a JavaScript example on this GitHub repository, I decided to give it a try by following the steps outlined in this helpful answer, while using Windows 7. Here's what I did: First, I installed node. Next, I installed browserify. The ...

Is it possible to integrate a JavaFX Application class into a JFrame window?

I am currently developing a 'Weather Station' application using JavaFX to create a live graph. I am wondering if it's possible to embed this graph within a JFrame alongside other components that I want to include. If it is feasible, could yo ...

It appears that using "object[prop]" as a name attribute does not function properly in HTML

After using console.log on the req.body I received this output: [Object: null prototype] { 'shoe[name]': 'Shoe Name', 'shoe[description]': '', 'shoe[pictures]': '', 'shoe[collections] ...

AngularJS UI-Grid not displaying JSON data

Just started learning AngularJS and everything was going smoothly until I hit a roadblock... I have been struggling to display the JSON data returned from my REST service call. While hard-coding a data array in my controller works fine, displaying the act ...

Error encountered while creating a bean from the class org.apache.struts.validator.DynaValidatorForm

An error occurs when trying to access a JSP page, throwing the following exception: Exception creating bean of type org.apache.struts.validator.DynaValidatorForm All other functionalities using this class are functioning properly. We are unable to deter ...

Javascript coding for monitoring health status using a three.js health bar

After updating to version r127, my health bar stopped working. I'm not sure what changes I need to make to get it working again. There seems to be an error with the shader in this version. Here is the code: Code: import * as THREE from './thre ...

How can you convert an epoch datetime value from a textbox into a human-readable 24-hour date format

I have an initial textbox that displays an epoch datetime stamp. Since this format is not easily readable by humans, I made it hidden and readonly. Now, I want to take the epoch value from the first textbox and convert it into a 24-hour human-readable da ...

retrieve fresh information from the API

Hello! I am attempting to retrieve new data from an API by filtering it with a JSON file. My goal is to filter the data from the API using the JSON file and extract any new information. const jsnf = JSON.stringify(fs.readFileSync("./data.json" ...

Using JavaScript to sort data within specific timeframes

How can I extract data based on timestamps greater than 06? "use strict" const data = [ {timestamp: "2020-04-23 05:05", totalAvg: 2.596211180124224}, {timestamp: "2020-04-23 05:10", totalAvg: 3.22052273203436}, {timestamp: "2020-04-23 05:15", t ...

Is it possible for the Jquery Accordion to retract on click?

Hello everyone, I've created an accordion drop-down feature that reveals content when the header of the DIV is clicked. Everything works fine, but I want the drop-down to collapse if the user clicks on the same header. I am new to JQUERY and have trie ...

Suggestions for placing a script under the scripts menu in Illustrator CS5.1

My script for Adobe Illustrator CS5.1 is not showing up in the scripts menu despite trying to place it in various directories such as: C:\Program Files\Adobe\Adobe Illustrator CS5.1\Presets\en_GB\Scripts\ C:\Progra ...

Choose the following span tag that comes after a specific HTML element using Jquery

I am attempting to locate the following span element with the class name slider-value after a specific HTML element has been selected. I have tried several solutions, but none of them seem to be working. While I could target it by utilizing the id, I pref ...

Error: Issue with hook function call detected. Struggling to locate exact source in React JS

As I dive into React for the first time, I'm working on creating a sign-up form with multiple steps. Despite reading through the material-ui documentation and learning about ReactJS, I'm struggling to pinpoint where I've gone wrong. Here&ap ...

Retrieve data from a particular XML document

I am trying to parse XML in Java. The XML structure is as follows: <Attributes><ProductAttribute ID="359"><ProductAttributeValue><Value>1150</Value></ProductAttributeValue></ProductAttribute><ProductAttribute I ...

What is the best way to separate a string value with commas and send it to a controller?

Within my SQL table named Products, there is a field called AvailableSizes with a data type of NVARCHAR, which stores all the available sizes for a product. In my view, I have separated the values of the AvailableSizes field as shown below: <p> ...

Callback function located within directive attribute specified in separate attribute

Recently, I created a directive called mySave, and it looks like this: app.directive('mySave', function($http) { return function(scope, element, attrs) { element.bind("click", function() { $http.post('/save', scope.d ...