Json array getting first data - javascript

I have an array which I declared as var myclinicsID = new Array(); and now, I push some data in it,when I alert it using alert(JSON.stringify(myclinicsID)) it gives me output of ["1","2","3","4"]
Now I want to use this for my function and when I look at in console, it gives me undefined, am I doing correct by my code :
getbarSeriesData(myclinicsID[0]['clinic_id'],data[i]['datemonths']);
I want to get myclinicsID first data element which is the value is 1

myclinicsID[0]['clinic_id']
Should be
myclinicsID[0]
All you need the array index. When you say myclinicsID[0]['clinic_id'], that is trying to get the clinic_id property of "1" which is obvious undefined.

Why myclinicsID[0]['clinic_id'] ? As there is nothing like clinic_id in your array.
Your array is single dimensional array. Hence, you can directly access the first element from an array using myclinicsID[0].
DEMO
var myclinicsID = new Array();
myclinicsID[0] = 1;
myclinicsID[1] = 2;
myclinicsID[2] = 3;
myclinicsID[3] = 4;
function getbarSeriesData(clientID) {
console.log(clientID);
alert(clientID);
}
getbarSeriesData(myclinicsID[0]);

Related

For loop not performing last function in array (JavaScript)

The last function in the boxFill() array is not being performed. I've tried accounting for the length of the array but to no luck. (I'm very new to js, just saying). It iterates through the first four indices, and always does not perform the last index, even when I change the position of the index.
var pResult1 = document.getElementById("result1");
var pResult2 = document.getElementById("result2");
var pResult3 = document.getElementById("result3");
var pResult4 = document.getElementById("result4");
var pResult5 = document.getElementById("result5");
var pResult = [pResult1,pResult2,pResult3,pResult4,pResult5]
function checkBox() {
/*var aFlor = [2.8,"Florida","Science"];
var bGeo = [3.5,"Georgia","Business"];
var cTex = [2.3,"Texas","Health"];
var dNew = [4.2,"NewYork","Law"];
var eMic = [3.9,"Michigan","Humanities"];*/
var boxValue = document.getElementById("searchBox").value;
var boxFill = [
function(){listBox('1','Florida state Scholarship','3.5','Florida','Applied Sciences')},
function(){listBox('2','Great Achievers Scholarship','4.0','Texas','Health')},
function(){listBox('3','Helpful Future Scholarship','3.0','Georgia','Business')},
function(){listBox('4','Never Give Up Scholarship','2.0','Michigan','Humanities')},
function(){listBox('5','Times Square Talent Scholarship','3.5','New York','Law')}
]
if (boxValue.includes("f")) {
for (i=0;i<boxFill.length+1;i++) {
boxFill[i]();
}
function listBox(number,name,gpa,state,major) {
pResult[number].innerHTML =
"<dl><dt>"+number+". "+name+"</dt><dd>- minimum GPA is: "+gpa+"</dd><dd>- You must live in "+state+"</dd><dd>- For the "+major+" major!</dd></dl>";
}
Is there a direct problem with the for loop or is it something in the array itself?
i<boxFill.length+1 should be i<boxFill.length, otherwise your loop iterates one more time than there are elements.
The function gets called, but it will throw an error because it tries to access an index in pResult that doesn't exist. If you open your browser's console you should see an error such as
Cannot read property 'innerHTML' of undefined
Arrays are zero-indexed in JavaScript. That means that pResult[0] will access the first element, pResult[1] accesses the second element, etc.
Now, the last function in boxFill tries to access pResult[5], i.e. the sixth element. But pResult only has five elements!
You need pass the values 0 to 4 to listBox, not 1 to 5:
var boxFill = [
function(){listBox(0,'Florida state Scholarship','3.5','Florida','Applied Sciences')},
function(){listBox(1,'Great Achievers Scholarship','4.0','Texas','Health')},
function(){listBox(2,'Helpful Future Scholarship','3.0','Georgia','Business')},
function(){listBox(3,'Never Give Up Scholarship','2.0','Michigan','Humanities')},
function(){listBox(4,'Times Square Talent Scholarship','3.5','New York','Law')}
]
Or if you want to pass 1-5 then you need to subtract 1 when accessing the index:
pResult[number-1].innerHTML = ...;

JS select value of multidimentional objects

So, I have following js setup:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
Then,
Then I get following result:
I am trying to select the individual value like below:
For example, I want to select "Sean" under "185"
var f = '185';
select_data = NAMES[f][0];
But I keep getting an error saying that "0" is not an identifier.
I am bit confused. Can someone help me out how to select the value properly?
You need to get the object inside the array first, so it should be as follows
var f = '185';
select_data = NAMES[0][f][0];
// -------^----- getting first element from array, which is the object

I want to insert values dynamically to hash map

var markerList1={};
var markerList=[];
and adding iterator values from the one for loop
function addSomething() // this function will multiple times from a for loop
{
image ='../css/abc/'+image[iterator]+'.png';
var data = respData[iterator];
var box = getbox(data);
var markerOpts = {
position : coordinates[iterator],
map : map,
icon :image,
title :data[1],
id : data[11]
};
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);
markerList1[markerOpts.title].push(vmarks);
}
whenever we call the function i want append the array's values to same index
markerList1[data[11]].push(vmarks);
but i'm not getting above result, when i markerList1[data[11]) then i'm getting only the last value i.e thirdvmark
i want output like this= markerList1[data[11]] = {firstvmark, secondvmark, thirdvmark};
You cannot do push to an object markerList1, only to an array.
change this
markerList1[markerOpts.title].push(vmarks);`
To this
markerList1[markerOpts.title] = vmarks;
markerList1[data[11]] is never initialized before you push something inside.
You can initialize it only once with a simple test:
if (! (data[11] in markerList1) ) {
markerList1[data[11]] = [];
}
markerList1[data[11]].push(vmarks);
Or in a shorter and safer way:
markerList1[data[11]] = markerList1[data[11]] || [];
markerList1[data[11]].push(vmarks);
(And please put data[11] in a variable)
Try this-
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);//you already pushing vmarks to array
markerList1[markerOpts.title]=markerList;//assign array to your markerList1 map

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

Categories

Resources