Friday, December 8, 2017

JavaScript Arrays, Hash Tables, and Objects

I’ve been writing a lot of JavaScript lately for SharePoint and when I need to store or manipulate lists of data I cannot remember the JavaScript rules and best practices for using arrays, hash tables, and objects. This post is to remind me of the techniques I’ve learned through research and trial and error.

Hint: You can cut and paste this code into JavaScript try it editor, like http://editor.javascriptkit.com/, and experiment.

JavaScript code

<script type='text/javascript'>

// Instantiate an array
var myArray = [];

// Instantiate a hash table
var myHash = [];

// Instantiate an object hash
var myObjects = []

// If you re-use any of these and need to clear, use the following
myArray.length = 0;
myHash.length = 0;
Object.keys(myObjects).length = 0;

// Add array elements
myArray.push('Dodge');
myArray.push('Audi');
myArray.push('Ford');

// Add hash entries
myHash['Dodge'] = 'RAM 1500';
myHash['Audi'] = 'S4';
myHash['Ford'] = 'Escape';

// Add has object entries
myObjects['Dodge'] = { model: 'RAM 1500', color: 'Blue' };
myObjects['Audi'] = { model: 'S4', color: 'Silver' };
myObjects['Ford'] = { model: 'Escape', color: 'Red' };

// Remove entries
myArray.splice(myArray.indexOf('Audi'), 1);
delete myHash['Audi'];
delete myObjects['Audi'];

// Determine if contains key
document.write('<b>Contains key...</b><br>')
if (myArray.indexOf('Dodge') >= 0) {
    document.write('- found "Dodge" in myArray!<br>');
}
if (myHash['Dodge'] != undefined) {
    document.write('- found "Dodge" in myHash!<br>');
}
if (Object.keys(myObjects).indexOf('Dodge') >= 0) {
    document.write('- found "Dodge" in myObjects!<br>');
}

// Iterate an array
document.write('<br><b>myArray iteration...</b><br>')
for (var i = 0; i < myArray.length; i++) {
    document.write('- myArray: ' + myArray[i] + '<br>')
}

// Iterate a hash
document.write('<br><b>myHash iteration...</b><br>')
for (var key in myHash) {
    document.write('- key/value: ');
    document.write(key + '/');
    document.write(myHash[key] + '<br>');
}

// Iterate a hash of objects
document.write('<br><b>myObjects iteration...</b><br>')
for (var key in myObjects) {
    document.write('- key/model/color: ');
    document.write(key + '/');
    document.write(myObjects[key].model + '/');
    document.write(myObjects[key].color + '<br>');
}

</script>

Output




1 comment: