How to store the values in hashmap in javascript - 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!!

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);

Related

Calculations on parsed JSON values produce NaN

I have a problem with some code. I started building a plugin for Chroma to insert data using JSON, but NaN is displayed to me.
My file content.js
var xmlhttp = new XMLHttpRequest();
var url = "http://rlinkit.neteasy.pl/abc.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr= Array();
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
for (i in arr) {
for(j in arr[i] ){
for(p in arr[i][j]){
out = arr[i][j][p].currency + arr[i][j][p].code + arr[i][j][p].bid + arr[i][j][p].ask + '<br>';
}
}
}
document.getElementById("id01").innerHTML = out;
}
My CodeHTML:
<div id="id01"></div>
<script src="content.js"></script>
My Output:
Edit (When I give the code - nothing is displayed.):
function myFunction(arr) {
var out = "";
var i;
var j;
var p;
for (var i = 0; i in arr.length; i++) {
for(var j = 0; j in arr[i].length; j++ ){
for(var p = 0; p in arr[i][j].length; p++){
out += arr[i][j][p].currency + arr[i][j][p].code + arr[i][j][p].buy + arr[i][j][p].sell + '<br>';
}
}
}
document.getElementById("id01").innerHTML = out;
}
To iterate over a JavaScript array, either use a for ... of loop or a traditional for loop. The syntax in your updated function (specifically, i in arr.length) is invalid JavaScript (looks like Python?).
Providing example data would help to improve this answer, but try some version of the following (updated to use ES6 let syntax, which you may want to revert to var):
function myFunction(arr) {
let out = "";
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
for (let p = 0; p < arr[i][j].length; p++) {
out += arr[i][j][p].currency + arr[i][j][p].code + arr[i][j][p].buy + arr[i][j][p].sell + "<br>";
}
}
}
document.getElementById("id01").innerHTML = out;
}

how to reverse order of xml using javascript

i want to reverse the order of this list using javascript i have tried different ways that i knew about it is
the below file show straight i want to reverse it.i dont know xml node much and how to get it reverse it totally
<messages>
<messageset>
<name>torje</name>
<time>1533904431</time>
<message>Vvvhjhf</message>
</messageset>
<messageset>
<name>moneyman</name>
<time>1533904437</time>
<message>njkjlmkmkl</message>
</messageset>
<messageset>
<name>anjali</name>
<time>1533904445</time>
<message>A hi fyi bk MLS egg FG ch bhi CDG jk IC</message>
</messageset>
</messages>
it the present code this shows order wise table like torje - Vvvhjhf , moneyman - njkjlmkmkl, anjali - A hi fyi bk MLS egg FG ch bhi CDG jk IC this should be reverse first anjali's msg then moneyman then torje's (sorry for bad typing in message)
function fetch() {
setTimeout( function() {
loadDoc()
fetch();
}, 100);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "../clubs/club.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>NAME</th><th>message</th></tr>";
var x = xmlDoc.getElementsByTagName("messageset");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
Can create an array and push each data row into the array then Array#reverse() that array and convert back to string using Array#join()
function myFunction(xml) {
var rowsArray =[]
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>NAME</th><th>message</th></tr>";
var x = xmlDoc.getElementsByTagName("messageset");
for (i = 0; i < x.length; i++) {
// new variable `row`
var row = "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
"</td></tr>";
// add row to array
rowsArray.push(row)
}
// reverse and return array to string
table += rowsArray.reverse().join('');
document.getElementById("demo").innerHTML = table;
}
Currently your for loop processes the messages in standard order.
for (i = 0; i < x.length; i++) {
You could just reverse this loop:
for (i = x.length - 1; i >= 0; i—-) {

Multidimentioanal arrays in JavaScript values not appending

I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);

AJAX/Javascript function not working

Hi I am using an ajax call to a function called build_Array. This function should break up myString which is "Call 1-877-968-7762 to initiate your leave.,1,0,through;You are eligible to receive 50% pay.,1,365,through;Your leave will be unpaid.,1,0,After;"
into sections divided by the commas into a 2d array. But it is not working. It says all of the values for the array are undefined. Here is where I call the function inside the ajax... (It works in the jsfiddle http://jsfiddle.net/ChaZz/3/)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var myString = request.responseText;
myString = build_Array(myString);
document.getElementById('ajax').innerHTML = myString;
}
}
And here is the function build_Array...
function build_Array (myString) {
var mySplitResult = myString.split(';');
var myArray = new Array(mySplitResult.length);
//may need to get rid of -1
for(var i = 0; i < mySplitResult.length -1; i++){
myArray[i] = new Array(4);
var mySplitResult2 = mySplitResult[i].split(',');
for(var z = 0; z < mySplitResult2.length; z++) {
myArray[i][z] = mySplitResult2[z];
}
}
var final_message = myArray[1][1];
return final_message;
}
http://jsfiddle.net/ChaZz/5/
var myString = "Call 1-877-968-7762 to initiate your leave.,-30,0,through;You are eligible to receive 50% pay.,0,365,through;Your leave will be unpaid.,365,0,After;";
function build_Array (myString) {
var mySplitResult = myString.split(';');
var myArray = [];
for(var i = 0; i < mySplitResult.length; i++){
myArray[i] = [];
var mySplitResult2 = mySplitResult[i].split(',');
for(var z = 0; z < mySplitResult2.length; z++) {
myArray[i][z] = mySplitResult2[z];
}
}
var final_message = myArray[1][1];
return final_message;
}
console.log(build_Array(myString)); // 0
There's no need for the loop to copy from mySplitArray2 to myArray, just assign the array returned by split directly to that element of the new array. And array.push can be used to build up an array incrementally.
function build_Array (myString) {
var myArray = [];
for (substring in myString.split(';')){
myArray.push(substring.split(','));
}
var final_message = myArray[1][1];
return final_message;
}

Creating New Select option at each time

I want to reset new values each time in the option list created JSON by the line:
var o=document.createElement("option");
document.getElementById("shipTo").options.add(o);
o.text= address[i];
But new option values are added in the list I want the no previous in the option:
var counter;
function GetAddress() {
var customerId = document.getElementById("invoiceTo").value;
var xml;
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else {
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
var address = JSON.parse(xml.responseText);
document.getElementById("billingAddress").value = address[0];
document.getElementById("shipAddress").value = address[0];
if (counter == 1) { {
for (var i = 0; i < address.length; i++) {
var removeMe = document.getElementById(o[i]);
removeMe.parentNode.removeChild(removeMe);
var o = document.createElement("option");
document.getElementById("shipTo").options.add(o);
o.text = address[i];
}
}
} else if (counter != 1) {
for (var i = 0; i < address.length; i++) {
var o = document.createElement("option");
document.getElementById("shipTo").options.add(o);
o.text = address[i];
}
}
counter = 1;
}
alert(counter);
}
xml.open("GET", "GenerateInvoice?customerId=" + customerId, true);
xml.send();
}
You need to clear the options first:
var oDDL = document.getElementById("shipTo");
while (oDDL.options.length > 0)
oDDL.options.remove(0);
If I understand correctly, you want to clear all the old options from the select element, before adding new options.
simply set options.length = 0;
example:
var o = document.createElement("option");
theSelect.options.length = 0;
o.text = '400';
theSelect.options.add(o);
http://jsfiddle.net/asaf/77sqX/4/
function GetAddress()
{
var customerId = document.getElementById("invoiceTo").value;
var xml;
if (window.XMLHttpRequest)
{
xml=new XMLHttpRequest();
}
else
{
xml=new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange= function()
{
if(xml.readyState==4 && xml.status==200)
{
var address= JSON.parse(xml.responseText);
document.getElementById("billingAddress").value=address[0];
document.getElementById("shipAddress").value= address[0];
var oDDL = document.getElementById("shipTo");//ship to id of the select in jsp
while (oDDL.options.length > 0)
{
oDDL.options.remove(0);//clears selects option each time
}
for(var i=0;i<address.length;i++)
{
var o = document.createElement("option");//creates optin
document.getElementById("shipTo").options.add(o);//adds option in the list
o.text= address[i];//inserts text in the option
}
}
}
xml.open("GET","GenerateInvoice?customerId="+customerId,true);
xml.send();
}

Categories