Splitting a String into an Associative Array

Started by beingchinmay, 09-23-2016, 06:19:03

Previous topic - Next topic

beingchinmayTopic starter

The split() method splits a string by a specified delimiter into a real instance of an Array object. For example:

var str = "a;b;c;d;e;f"
var ar = str.split(";") // ar[0] == "a", ar[1] == "b", ar[2] == "c", ...


Let's use the split() method to create a function named
associativeSplit() as a prototype of the String object:


function associativeSplit(del)
{
var tempAr = new Array()
tempAr = this.split(del)
var ar = new Obj() // not an array, just an object
for (var i = 0; i < tempAr.length – 1; i += 2)
{
ar[tempAr[i]] = tempAr[i + 1]
}
return ar
}
function Obj() { }
String.prototype.associativeSplit = associativeSplit


Notice the use of an empty function to create an object. At first, the function splits the string via the regular method into a regular array. It then loops through the array, using the next element as the key of an element in the associative array and its following element as the value of the same element in the associative array. Upon completion, the function returns the associative array. The function is then declared as a prototype of the built-in String object, applying to all strings. Now take a look at an example .


var str = "a b c d e f"
var ar1 = str.associativeSplit(" ")
document.write(ar1.a + "<BR>")
document.write(ar1.b + "<BR>")
document.write(ar1["c"] + "<BR>")
document.write(ar1["d"] + "<BR>")
// document.write(ar1[e] + "<BR>")
document.write(ar1.f + "<BR>")