Working with positional array values in javascript doesn’t have to be so hard

Kevin Altman
Adorable
Published in
2 min readSep 21, 2017

We don’t always have the luxury of working with beautifully crafted APIs. Sometimes we have to interface with APIs that include arrays requiring knowledge of what each position in the array maps to.

Take this data structure for example:

{
userPreferences: [
'pizza',
'seafoam green',
'42'
]
}

If you have knowledge of this array structure, then you would know that…

userPreferences[0] // Favorite Food
userPreferences[1] // Favorite Color
userPreferences[2] // Favorite Number

This is kind of whack. This is not at all obvious. A typical solution is to add comments to the code block to document what each means. Something like:

function setPreferences (response) {
// 0: Favorite Food
// 1: Favorite Color
// 2: Favorite Number

myApp.preferences = response.userPreferences;
}

This is helpful, but not very scalable.

A better option

Instead of trying to remember the intent, why not, instead, make those references a part of your application. I propose a dictionary based solution.

/*In this example, `response` is the response from an API request, and evaluates to the following:  {
userPreferences: [
'pizza',
'seafoam green',
'42'
]
}
*/var userPreferencesDict = [
'favoriteFood',
'favoriteColor',
'favoriteNumber',
];
function Dictionary (dict, array) {
return new Proxy([dict, array], {
get ([keys, values], key) {
const index = keys.indexOf(key);
return values[index];
},
set ([keys, values], key, value) {
const index = keys.indexOf(key);
values[index] = value;
return value;
}
});
}
const preferences = new Dictionary(userPreferencesDict, response.userPreferences);
preferences.favoriteFood; // => pizza
preferences.favoriteColor; // => seafoam green
preferences.favoriteNumber; // => 42

Now, you can reference the array data by it’s keyed definition. Sweet!

If you’re not able to use Proxy in your application, I’ve included other possible implementations here.

Note: Proxy is available from node 6.0+ and in the browser: Chrome 49+, Firefox 18+, Opera 36+, Safari 10+, and on all mobile browsers.
More on Proxy

Let me know if you have other solutions that you’ve used!

--

--

Kevin Altman
Adorable

Creative Director. Developer. Designer. Lover of humans (and animals) @adorableio. Creator of things you might use http://github.com/itsthatguy