Undefined values in Javascript object - javascript

So I am trying to store an array of objects into localStorage, as follows:-
EDIT: The following is part of a function that is called in a loop.
c = [{"name":nameDOM.value,"add":+addDOM.value,"town":townDOM.value,"post":postalDOM.value,"mob":mobDOM.value}];
cData = cData.concat(c);
localStorage.setItem('cData', cData);
However, after a page refresh, when I try to access data from the objects, it is apparently undefined. Accessing data from the objects is fine before a refresh.
I am accessing the data in the following manner:-
//Table code omitted.
var text = document.createTextNode(""+cData[i].name+", "+cData[i].add+", "+cData[i].town+", "+cData[i].post+", "+cData[i].mob+"");
I have been trying to debug the problem using Chromes Javascript tools, as well as inserting alerts into various places to monitor the state of the variables; still undefined.

You've made an oopsies. Try:
c = [{"name":nameDOM.value,"add":+addDOM.value,"town":townDOM.value,"post":postalDOM.value,"mob":mobDOM.value}];
cData = cData.concat(c);
localStorage.setItem('cData', JSON.stringify(cData));
They difference being that you are turning your array of objects into a json string that can be parsed later by your code using:
eval(localStorage.getItem('cData'));

Related

How is data stored in arrays from getValue

In Google Sheets looking as part of a script to store data in a range to an array then to check whether a certain column has an "Y" in so I can loop through and store these columns in new arrays.
I have the following code but am getting this error - "TypeError: Cannot read property "0.0" from undefined."
var data = sheet.getRange("A6:U37").getValues;
if (data[20][i]=="Y"){
(The if code is generating the error)
Believe I am misunderstanding how the range is stored in the array causing the error any advice?
In the first line of code you provided, you are referencing the function getValues rather than actually calling it. In order to do so, you just have to modify the code as follows:
var data = sheet.getRange("A6:U37").getValues();
if (data[20][i]=="Y"){
Next time you have issues similar to this one, you can consider using logging or other debugging techniques in order to debug your script.

Setting Object to Chrome Storage

So I'm trying to save an object via the chrome.storage API. The relevant code is:
var images = null;
var storage = chrome.storage.sync;
var key = "key";
images = getImages(source);
alert(images.length); // returns 4
storage.set({key: images});
storage.get("key", function(result) {
alert(result.length); // returns undefined
});
I'm tested that immediately after the getImages() function, images is a wrapped set JQuery object with a length of 4. However, when I try to access images.length via the storage.get callback, the result is undefined.
Could someone help identify the error in how I am storing and/or retrieving this JQuery object?
Update 1:
Thank you all for your help. As clarification for the use case, I am using chrome.storage instead of localStorage because I plan to pass extension info to another script.
Fortunately, TranQ/Xan's solution has enabled me to access the array via the storage.get call.
I'm still experiencing issues working with the wrapped set JQuery object stored in the array but I'll post a separate question since the current solution encapsulates broader use cases.
TranQ's comment is on point.
Presumably, images is an array. You store that array under the "key" key.
When you execute the get() function, it returns an object populated with all key-value pairs you asked, even if you only ask for one key.
So, result is an object {key : [/* something */]}. Objects do not have a length property, and you get undefined
You need to use result.key (or result["key"]) to access your array.

Javascript: get the number of json objects when using #Html.Raw

To get a list of c# objects I'm using the following Javascript code:
var objectList= '#Html.Raw(Json.Encode(Model.ObjectList))';
How would I get the number of objects within objectList?
I tried using .length and .size().
What you are setting is a string type to objectList, try:
var objectList = #Html.Raw(Json.Encode(Model.ObjectList));
console.log(objectList.length);
Inspect the DOM in F12 tools to make sure the JSON is correct.

Object in javascript stuck on last line of csv file

Im currently trying to build a choropleth on the map of Puerto Rico using D3. Using Scott Murray's Example on Choropleths, I'm trying to bind data to each municipality of Puerto Rico. I have a placeholder empty object to hold the data being fed from the CSV like so:
var properties = {};
Then, I proceed to read the CSV file by row. I assign the corresponding values to some variables like so:
properties.dataID = parseFloat(data[i].id);
properties.dataMunic_Total = parseFloat(data[i].municipio_total);
//etc.
All fine and dandy. I console.log to check whether or not the data was stored correctly:
console.log(properties.dataID);
//Displays 1, which is correct.
However, when I try to access the whole object:
console.log(properties);
it only displays the last row of the CSV file. I ran that last console.log() statement inside the first for loop, immediately after assigning the data to the object's properties, and every time the loop iterates through the console.log(), it ONLY displays the last line of the CSV file.
When I try to assign the object properties to my map's objects (municipalities), all that it ever assigns is that last line of the CSV file. So I tried setting them up individually, seeing that seems to have worked. However, JavaScript complains that the property does not exist in the object:
obj.geometries[j].properties.year[properties.dataYear - 2000].id = properties.dataID;
Uncaught TypeError: Cannot read property 'id' of undefined
I tried initializing it as if it were a new variable:
var obj.geometries[j].properties.year[properties.dataYear - 2000].id = properties.dataID;
but then I got this back on the console:
Uncaught SyntaxError: Unexpected identifier
Aside from the syntax error, I think that this is mainly due to the fact that I appended an array to each municipality so I could hold different sets of data per year... but I don't understand why JavaScript behaves this way.
My question is: why does my object behave this way? Is there something wrong with d3.csv? Am I doing something wrong?
If you want to store several properties, you need to use an array (i.e. a list). In the code you are using, you are only creating a single variable properties at a time and not saving the references to the ones you have created previously. That is, in each iteration of the loop, you are creating a new object, but losing the old one.
If you declare properties as an array and then append new property objects in the loop, you can reference them later and use them to draw the map. The code would look something like this.
var properties = [];
for(var i = 0; i < data.length; i++) {
var property = {};
property.dataID = parseFloat(data[i].id);
property.dataMunic_Total = parseFloat(data[i].municipio_total);
// ...
properties.push(property);
}
After setting up the data like this, you should be able to proceed as described in the example.

JSON parsing a Titanium.App.Properties string

In an app, made with TideSDK; i assign a global variable (shocking I know) to a the JSON parse of a string stored in Titanium.App.Properties:
var workbookArray = JSON.parse(Titanium.App.Properties.getString('workbookArray'));
workbookArray is an array of objects.
And then on the unloading of a page, I assign Titanium.App.Properties string the value of workbookArray, which may have been changed by whoever has used the app:
Titanium.App.Properties.setString('workbookArray', JSON.stringify(workbookArray));
Each time I open the app, however, I'm told that JSON was unable to parse the first code snippet (initializing workbookArray).
Aside from this issue, I don't expect to use the app Properties API for my storage needs in the longterm, I wish i could use indexedDB with titanium. SQL is an option, but is a little messy when it comes to objects. Any other suggestions for a database solution?
Try getList and setList
http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.App.Properties
What is stored in the list?

Categories

Resources