Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  168] [ 7]  / answers: 1 / hits: 21443  / 11 Years ago, sat, september 7, 2013, 12:00:00

I'm sorry if this has been asked before, it's something that's difficult to search for...



I want to use a javascript Array to hold objects, with the key as the ID



for example, let's say I had a bunch of people who had different IDs



 var people = new Array();
var person = {property: value}; // this is person ID 4

var people[4] = person;


I want to be able to then reference that user by saying, people[ID].propery



The problem is that the output of this array now would be;



 null,null,null,null,object


Because it's expecting the keys to be 0,1,2,3,4



Am I being stupid or something? :-) We can do it for strings right, so why not non-sequential numbers?



What I'm trying to avoid is having to loop over every single object in the array every time I want to access a particular person inside it, therefore I figured that using the ID number as the key would work



Thanks guys! :-)


More From » arrays

 Answers
32

Use a dictionary object



var people = {};
people[4] = 'me';

[#75835] Thursday, September 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;