简体   繁体   中英

Javascript hash map with 2 values

Is There a way to do an hash map in javascript that holds 1 key and 2 values?

For an hash map with key and value in javascript i can do something like this:

var userList = {
     11234321:"koko",
     22342342:"jojo",
     32342423:"fofo",
     42342342:"momo"                    
    }

So for each ID number i have user name.

Now, i want to add another value, like: user age.

There is a way to do that? any other solution to the problem?

I'd recommend having the value as another hash

var userList = {
    11234321: {
        username: 'koko',
        age: 44
    }
}

Essentially what you're asking for is a multidimensional associative array. The JavaScript implementation of that is nested objects, along these lines:

var userList = {
    11234321:{
        "username": "koko",
        "age": 24
    },
    22342342:{
        "username": "jojo",
        "age": 33
    },
    ...
};

Note that there is no limit to how deep these nests go.

To access a particular username, for example, you would access userList[id]['username'] (or userList[id].username ), just like an associative array in other languages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM