This is trivial I know but I'm so used to OOP languages. I'm trying to figure out how to write out each name/value in either one alert or many, just so I can verify the data
var dCookieNameValuePairs = {};
for (i = 0; i < cookieValues.length; i++)
{
var akeyValuePair = aCookieValues[i].split("=");
dCookieNameValuePairs[keyValuePair[0]] = keyValuePair[1];
}
// display each name value pair testing
for (i = 0; i < dCookieNameValuePairs.length; i++)
{
alert("Name: " + dCookieNameValuePairs[] + "Value: " +
}
I'm stuck at the second for loop...I am not sure how to iterate through the dictionary and then focus on each name/value to spit it back.
You want to use for..in for enumerating through a dictionary/map.
for ( var prop in dCookieNameValuePairs ) {
if ( dCookieNameValuePairs.hasOwnProperty( prop ) ) {
alert( dCookieNameValuePairs[prop] )
}
}
I may have typo'd. Only use .length when you are dealing with an array [] or a custom array-like object that you defined to have .length populated.
for (i in dCookieNameValuePairs) {
alert("Name: " + i + " Value: " + dCookieValuePairs[i]);
}
See the "JavaScript Does Not Support Associative Arrays" section of this page for more details.
If you don't need an associative array, you might put the keys and values into an array of objects instead. So your first loop would look something like this:
for (i = 0; i < cookieValues.length; i++) {
var akeyValuePair = cookieValues[i].split("=");
dCookieNameValuePairs.push({key: akeyValuePair[0], value: akeyValuePair[1]});
}
Related
I have this array of objects being loaded:
$(document).ready(function () {
$("<div></div>").load("/Stats/Contents #stats", function () {
statcount = $(".list-group-item", this).length;
for (var j = 0; j < statcount; j++) {
statList.push(stat);
}
for (var i = 0; i < statcount; i++) {
statList[i].statId = document.getElementById("statId-" + (i + 1) + "").value;
statList[i].productDescription = document.getElementById("productType-" + (i + 1) + "").value;
statList[i].lastMeasuredInventoryAmount = document.getElementById("statLastMeasureAmount-" + (i + 1) + "").value;
}
)}
)}
.... and so on
Then I get the changed values and save them, however, in the ajax post call, all of the array objects are same (the last one assigned), looks like they get overwritten.
Any ideas? I saw these deferred/promise type code but not sure if there's simpler way.
Thanks.
It sounds like you take the statList array and then push that up to the server, with any respective change. Rather than building and maintaining a list like this, have you thought of switching it around and just grabbing the results out of the markup and building up the array at save point?
$("btnSave").on("click", function(e) {
var data = [];
$(".list-group-item").each(function() {
data.push({
statId: $(this).find(".statid").val(),
.
.
})
});
You wouldn't need to give every element an ID (but could) as my sample uses CSS classes to find the element within the current list item. Additionally, if these are inputs, you could serialize them from the root element more efficiently...
I have two fields I need to pull data from in SQL and put that into an array or list that I can loop through. Then for each loop, I do something based on both the fields for each index. What is the best method for this? I thought maybe a dictionary or possibly creating an object?
Right now I pull the fields into two seperate arrays, and I loop through both at the same time, but I am finding that sometimes one array has a blank value, and then they get out of sync and I have issues. This seems like a terrible implementation anyway.
How can I put these into a key value pair and then act on the data?
Edit: I should note that my SQL code just returns a bunch of comma seperated values. So it was easy to create an array out of those, but its proving more difficult to create anything else such as an object because I get all the values at one time.. :(
var equipIDArray = //SQL Gathering code here
var equipTypeArray = //SQL gathering code here
for(var cnt = 0; cnt < equipIDArray.length; cnt++){
alert(cnt);
if(isNaN(equipIDArray[cnt]) === true){
equipIDArray[cnt] = '';
}
switch(equipTypeArray[cnt]){
case 'Blower' :
alert('test1');
break;
case 'Dehumidifier' :
alert('test2');
break;
default :
alert('default');
}
}
It' easy to translate your arrays into an object if they just represent key/value pairs. Then you have an object you can use like a dictionary:
var equipIDArray = ["Blower","Humidifier","Lawn Mower"];
var equipTypeArray = ["Leaf blower","Whole House Humidifier","Honda Brand"];
var equipment = {};
for(var i = 0; i < equipIDArray.length; i++) {
equipment[equipIDArray[i]] = equipTypeArray[i];
}
for(property in equipment) {
console.log(property + " : " + equipment[property]);
alert(property + " : " + equipment[property]);
}
i've got this code to list all saved players in a game:
function getAllPlayers(){
for (var i = 0; i <= playerCount; i++){
object[i] = JSON.parse(localStorage.getItem("savedData"+i));
console.log(object[i]);
}
}
I get object[object], which is a collection of objects. In console, I get to see their properties and values, however with:
for (var name in object) {
alert('"' + name + '"="' + object[name] + '"');
}
I still cannot access these properties. Is there a method to get each object into a separate variable, so that I can access them via varName.property syntax?
The problem is because object is not really an object this is array of objects and you should access property of some object in this array
for (var i = 0; i < object.length; i++)
for (var name in object[i]) {
alert('"' + name + '"="' + object[i][name] + '"');
}
//currently you have to read it like this
for (var i = 0; i < object.length; i++){
var singleObj = object[i][0]; // additional 0 index
for (var name in singleObj) {
alert('"' + name + '"="' + singleObj[name] + '"');
}
}
like you are using it here
console.log(object[i]);
If your problem is that you are getting [object Object] in your alert() box:
alert(someObject) calls native Object.toString() method of an argument passed, that is why you are getting [object Object].
Use JSON.stringify(someObject) to simply convert your object to JSON string, or implement your own method to generate a string from an object.
Hi I've searched for the answer but since the tutorials online are all friends = ("bob","fred","joe"); I dont get anywhere. I would like to be able to store several objects with 1-3 values in each index of the array like:
map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
The object I have right now looks like:
node = {};
node = {ground:0, object:1};
But when I try the array way I can't access it, all I get "object Object". What would be the correct way to get the values from the map array one by one?
Do you mean:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}];
for(var i = 0; i < map.length; i++) {
console.log(map[i].ground + " item " + map[i].item);
}
Not sure what you want, or what you mean by "the array way", but if you want to get all the values for say ground, then:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
for (var i=0, iLen=map.length; i<iLen; i++) {
alert(map[i].ground);
}
Edit
...
alert('item ' + i + ' : ' + map[i].ground); // item 0 : 0
...
[
{"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"},
{"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"}
]
Above is my JSON Data
var searchBarInput = TextInput.value;
for (i in recentPatientsList.length) {
alert(recentPatientsList[i].lastName
}
I am getting the alert for this. Now i have a TextInput which on typing should search the Json and yield me the result. I am searching for lastname value.
How would i take the value and search in my JSON.
This:
var searchBarInput = TextInput.value;
for (i in recentPatientsList.length) {
alert(recentPatientsList[i].lastName); // added the ) for you
}
is incorrect. What you should do to iterate over an array is:
for (var i = 0; i < recentPatientsList.length; ++i) {
alert(recentPatientsList[i].lastName);
}
The "for ... in" mechanism isn't really for iterating over the indexed properties of an array.
Now, to make a comparison, you'd just look for the name in the text input to be equal to the "lastName" field of a list entry:
for (var i = 0; i < recentPatientsList.length; ++i) {
if (searchBarInput === recentPatientsList[i].lastName) {
alert("Found at index " + i);
}
}
You should not use for..in to iterate over an array. Instead use a plain old for loop for that. To get objects matching the last name, filter the array.
var matchingPatients = recentPatientsList.filter(function(patient) {
return patient.lastName == searchBarInput;
});