Rajat Krishnan
Rajat Krishnan

Reputation: 35

How to store the values in hashmap in javascript

I am parsing xml file in javascript and i am extracting all its values

function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  myFunction(this);
}
};
xmlhttp.open("GET", "/ccm/rpt/repository /workitem?fields=workitem/projectArea/*", true);
xmlhttp.send();
}

function myFunction(xml) {
var x,y,j, i, xmlDoc, txt,txt1;
xmlDoc = xml.responseXML;
txt = "";
txt1="";
x = xmlDoc.getElementsByTagName("contextId");
for (i = 0; i< x.length; i++) {
txt += x[i].childNodes[0].nodeValue;

}
y = xmlDoc.getElementsByTagName("name");
for (j = 0; i< y.length; j++) {
txt1 += y[j].childNodes[0].nodeValue;
}
}

and now my target is to store the value of name as key and contextId as value (HashMap concept) , So is it possible to achieve the same,Also please let me if my question sounds ambiguous Thanks in advance!!

Upvotes: 0

Views: 654

Answers (1)

Johan
Johan

Reputation: 1515

You can add properties to objects as if they were hashmaps, have a look at this example:

var myObj = {prop1: 12};
var propName = "prop2";

myObj[propName] = 10;

console.log(myObj);

Which outputs:

{prop1: 12, prop2: 10}

In your example, lets assume x and y are of equal length, then we can add to the object in a single loop:

var x,y,j, i, xmlDoc, myHashMap;

xmlDoc = xml.responseXML;
myHashMap = {};

x = xmlDoc.getElementsByTagName("contextId");
y = xmlDoc.getElementsByTagName("name");

for (i = 0; i< x.length; i++) {
  var value = x[i].childNodes[0].nodeValue;
  var key = y[i].childNodes[0].nodeValue;
  myHashMap[key] = value;
}

console.log(myHashMap);

Upvotes: 1

Related Questions