user243540
user243540

Reputation:

Using an integer as a key in an associative array in JavaScript

When I create a new JavaScript array, and use an integer as a key, each element of that array up to the integer is created as undefined.

For example:

var test = new Array();
test[2300] = 'Some string';
console.log(test);

will output 2298 undefined's and one 'Some string'.

How should I get JavaScript to use 2300 as a string instead of an integer, or how should I keep it from instantiating 2299 empty indices?

Upvotes: 125

Views: 135846

Answers (11)

Jesuslg123
Jesuslg123

Reputation: 735

As people say, JavaScript will convert a number to a string, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.

You can create your object:

var object = {};

And add the values as array works:

object[1] = value;
object[2] = value;

This will give you:

{
  '1': value,
  '2': value
}

After that you can access it like an array in other languages getting the key:

for(key in object)
{
   value = object[key] ;
}

Upvotes: 25

malac usp
malac usp

Reputation: 31

Simple solution if you would rather use an array. When adding the number just preface it with a letter.

e.g.

let ctr = 3800;
let myArray=[];
myArray["x" + ctr.toString()]="something";
myArray["x" + (ctr+1).toString()]="another thing";

Then just add the "x" in access routines that call the number as an index. e.g.: console.log( myArray["x3800"] ); or: console.log( myArray["x"+ numberOfYourChoice.toString()] );

Upvotes: 1

Claudiu
Claudiu

Reputation: 229341

Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

var test = {}
test[2300] = 20;
console.log(test["2300"]);

Upvotes: 148

wordbug
wordbug

Reputation: 671

Compiling other answers:

Object

var test = {};

When using a number as a new property's key, the number turns into a string:

test[2300] = 'Some string';
console.log(test['2300']);
// Output: 'Some string'

When accessing the property's value using the same number, the number is turned into a string again:

console.log(test[2300]);
// Output: 'Some string'

When getting the keys from the object, though, they aren't going to be turned back into numbers:

for (var key in test) {
    console.log(typeof key);
}
// Output: 'string'

Map

ECMAScript 6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ECMAScript 6 compatibility table looks green enough for your purposes, consider using a Map:

var test = new Map();
test.set(2300, 'Some string');
console.log(test.get(2300));
// Output: 'Some string'

No type conversion is performed, for better and for worse:

console.log(test.get('2300'));
// Output: undefined
test.set('2300', 'Very different string');
console.log(test.get(2300));
// Output: 'Some string'

Upvotes: 12

Pragmateek
Pragmateek

Reputation: 13364

If the use case is storing data in a collection then ECMAScript 6 provides the Map type.

It's only heavier to initialize.

Here is an example:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

Upvotes: 24

pictus
pictus

Reputation: 77

Sometimes I use a prefixes for my keys. For example:

var pre = 'foo',
    key = pre + 1234

obj = {};

obj[key] = val;

Now you don't have any problem accessing them.

Upvotes: 0

Jason Williams
Jason Williams

Reputation: 2860

Get the value for an associative array property when the property name is an integer:

Starting with an associative array where the property names are integers:

var categories = [
    {"1": "Category 1"},
    {"2": "Category 2"},
    {"3": "Category 3"},
    {"4": "Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through the array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // Log progress to the console
        console.log(categoryid + ": " + category);
        //  ... do something
    }
}

Console output should look like this:

1: Category 1
2: Category 2
3: Category 3
4: Category 4
2300: Category 2300
2301: Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the JSON content you would have if you serialized a Dictionary<string, string>[] object.

Upvotes: 2

Upperstage
Upperstage

Reputation: 3757

Use an object - with an integer as the key - rather than an array.

Upvotes: 0

bdukes
bdukes

Reputation: 155925

Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.

var test = {};
test[2300] = 'some string';
console.log(test);

Upvotes: 4

Jeff Hammerbacher
Jeff Hammerbacher

Reputation: 4236

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';

Upvotes: 3

Annie
Annie

Reputation: 6631

You can just use an object:

var test = {}
test[2300] = 'Some string';

Upvotes: 37

Related Questions