Shaun
Shaun

Reputation: 2181

Can you give an object a key in javascript?

If you have an array of objects like

[{rID:53, name:Roger, age:43},{rID:12, name:Phil, age:22}]

is it possible instead to give each a object a key like

 [53:{name:Roger, age:43},12:{name:Phil, age:22}]

?

I understand that each object has an index number, but I'm looking for a way to find objects not based on their index pos, and preferably without having to loop through until you find an object with rID=53 type thing.

I'd be using PKs from mysql rows to give each object it's key.

Cheers

Upvotes: 2

Views: 101

Answers (4)

Joseph
Joseph

Reputation: 119867

You need an object for that.

{
  53: {
    name: "Roger",
    age: 43
  },
  12: {
    name: "Phil",
    age: 22
  }
}

Upvotes: 2

Populus
Populus

Reputation: 7680

You can use objects to do this

var map = {"53":{"name": "Roger", "age": "43"},"12":{"name": "Phil", "age": "22"}};

Then access the value like an array (note, i'm using string because that's what keys are stored as, strings, you can access it using an integer, but it will just be converted to a string when searching for the property anyway):

map["53"]

You can also loop through this map object:

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

Upvotes: 1

Bergi
Bergi

Reputation: 664969

No. You cannot have a key and an index in a js array. Arrays only have indices, Objects only have keys. There is no such thing like a associative array in JavaScript. If the order (of your original array) does not matter, you can use an object though:

{53:{name:"Roger", age:43},12:{name:"Phil", age:22}}

Upvotes: 1

Quentin
Quentin

Reputation: 943999

If you want an unordered collection of variables with arbitrary keys. Then use an object.

{"53":{name:Roger, age:43},"12":{name:Phil, age:22}}

Arrays can have only numeric keys, but if you want to assign a value to an arbitrary position, you have to do so after creating the array.

var some_array = [];
some_array[53] = {name:Roger, age:43};
some_array[22] = {name:Phil, age:22};

Note that this will set the array length to 54.

Note that in both cases, you can't have multiple values for a given property (although you could have an array of values there).

Upvotes: 2

Related Questions