Is there an equivalent object in Javascript similar to Pair object from Java?

Viewed 309

There is an object in Java that comes from javafx.util library. You can use it to return 2 value as method return value. I wonder if there is an equivalent Object in Javascript. I can use regular Map() object for my purpose but I would like to know if there is something special for this purpose in Javascript too as it exists in Java.

2 Answers

The mentioned Pair object exists of a key and a value field. As Javascript is a dynamic language I would suggest to simply use an object like

function () {
    const pair = {
        key: 'someKey',
        value: 'some value'
    };
    return pair;
}

or even

function () {
    const pair = {
        'someKey': 'someValue'
    };
    return pair;
}

But to my knowlege there is no dedicated pair object in the Javascript language.

There is an object in Java that comes from javafx.util library.

In fact, standard Java (JDK) does not have a Pair class. The class javafx.util.Pair is a JavaFx class, not a JDK class. Since JDK 11, JavaFx is a separate project maintained by OpenJFX community. The closest thing to a 'pair' notion JDK has is Map.Entry.

Map.Entry <String, Integer> pair = 
    new AbstractMap.SimpleEntry <>();

In JavaScript, defining a 'pair' is much simpler.

var pair = {key1: "value1"};
console.log(pair.key1);

Related