Thursday 18 April 2019

JavaScript name:value pairs

The following JavaScript code looks at using name:value pairs when storing multiple bits of data within an array. This was recently shown to me by a colleague who used it instead of the default method of picking an item from an array by calling its position. In their example they were using it to capture multiple errors which could occur if data was missing when running a function. For this example I am just extracting a few items of data to explain the concept.

Traditionally (and throughout most of my scripts up to this point) I have extracted data from an array by calling its position only and storing the value in a variable such as this:
var data = [surname, postcode, shoeSize];
var surname = data[0];
var postcode= data[1];
var shoeSize= data[2];
This works perfectly except if you scale it up and have an array with 10+ items for instance and you are not necessarily extracting them in a sequential list. By using name:value pairs however what we can do is assign a label (name) to the specific piece of data (value) within an array:
var data = {surname:surname, postcode:postcode, shoeSize:shoeSize};
var surname = studentData['surname'];
var postcode = studentData['postcode'];
var shoeSize = studentData['shoeSize'];
So rather than calling the position of the value in the array we can now call its name, which will help to reduce errors when dealing with large arrays. This has the added benefit of your code being somewhat easier to understand by others as they can deduce more quickly what data you are calling. The trade-off is that a little bit more thought needs to go into creating the name:value pairs in the first instance.

Below is some sample code for you to test this method out.

name:value pairs javascript.xlsx

No comments:

Post a Comment