Key/Value pair with Ionic/Angular


#1

Coming from developing in Java and having ready access to the HashMap<K,V> at all times must have really spoiled me. I understand in JavaScript there’s not any colletions like this, and you’re forced to either use Objects or arrays.

Here’s my issue, let’s say I want to map an account id to some information.

var accounts = [[]];  // Multidimensional array.

var account = {
    id: 9205236,
    username: "John",
    password: "Doe"
};

accounts[account.id] = account;

The (issue?) with this is that this creates an array with X indecies, where X is the maximum account number stored. In this example this array has 9,205,236 index values stored as null. This can’t be efficient.

The other approach is to store objects, like so.

var accounts = []; // Single Dimensional array

var account = {
    id: 9205236,
    username: "John",
    password: "Doe"
};

accounts.push(account);

This will store an account object (containing the id) at the next index. Thus creating much less garbage. The issue I’ve come up with is accessing this object with Angular.

For the first example it’s simple:

<p>Hello {{accounts[id].username}}, how are you doing?</p>

However I can’t find a way to do this with the second (more efficient) approach. Because you can only access the array by the index. So, if John happened to be the first account added to the array, it’d be accounts[0] however there’s no way of telling when or where John was added, or if John even exists in most applications.

Any tips?