Why Is My JavaScript Object Throwing An Undefined Error? - javascript

I am getting this error in my console:
Uncaught TypeError: Cannot read property 'kbsrc' of undefined
I get this error because I think there may be something wrong with the way I created my JavaScript Object. I have never created an object that is as multidimensional as this one so I am probably screwing up the syntax somewhere. I generate the objects in the mark-up file here:
var kb_work = {}
kb_work['2014'] = {};
kb_work['2014']['kbid'] = ["51","47"];
kb_work['2014']['kbsrc'] = ["images\/images-4.jpeg","images\/imgres-3.jpeg"];
kb_work['2014']['kbtitle'] = ["shalom","Test 6"];
kb_work['2014']['kbmedium'] = ["2x2","Oil"];
kb_work['2014']['kbsize'] = ["2x2","2x6"];
kb_work['2014']['kbdate'] = ["2014","2014"];
kb_work['2013'] = {};
kb_work['2013']['kbid'] = ["55","54","53","52","50"];
kb_work['2013']['kbsrc'] = ["images\/imgres-4.jpeg","images\/imgres-3.jpeg","images\/imgres-1.jpeg","images\/images.jpeg","images\/images-3.jpeg"];
kb_work['2013']['kbtitle'] = ["totally","heheh","Howdy","tickle","hi"];
kb_work['2013']['kbmedium'] = ["oil","oil","2x2","o","oil"];
kb_work['2013']['kbsize'] = ["2x2","2x2","2x2","2x2","2x1"];
kb_work['2013']['kbdate'] = ["2013","2013","2013","2013","2013"];
kb_work['2012'] = {};
kb_work['2012']['kbid'] = ["49"];
kb_work['2012']['kbsrc'] = ["images\/images-2.jpeg"];
kb_work['2012']['kbtitle'] = ["chicked"];
kb_work['2012']['kbmedium'] = ["oil"];
kb_work['2012']['kbsize'] = ["3x4"];
kb_work['2012']['kbdate'] = ["2012"];
Each of these arrays have only one value right now, but will grow as the user adds work. Following this I link to a file, which contains this function (I commented on the specific line) that the TypeError refers to:
function changeGal(gallery_year) {
$("#gallery-control-bar").fadeOut(t);
$("#gallery-image").fadeOut(t);
$("#info").fadeOut(t);
$("#gallery-viewer").fadeOut(t);
//this is where the script chokes up referring to "currentImg" which is 0 and refers to the first value in the array "['2014']['kbsrc']".
$("#gallery-image").html("<img src='" + kb_work[gallery_year]['kbsrc'][currentImg] + "'>");
$("#gallery-title").html(kb_work[gallery_year]['kbtitle'][currentImg]);
$("#gallery-medium").html(kb_work[gallery_year]['kbmedium'][currentImg]);
$("#gallery-size").html(kb_work[gallery_year]['kbsize'][currentImg]);
$("#gallery-date").html(kb_work[gallery_year]['kbdate'][currentImg]);
$("#gallery-control-bar").delay(t + d).fadeIn(t);
$("#gallery-image").delay(t + d).fadeIn(t);
$("#info").delay(t + d).fadeIn(t);
var userCurrent = currentImg + 1;
var userTotal = kb_work[gallery_year][0].length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
Any thoughts to why it cannot reference the value?

I think you need
$("#gallery-image").html("<img src='" + kb_work[gallery_year][gallery_year + '.kbsrc'][currentImg] + "'>");
because it looks like gallery_year is a year value like 2013, but the key is a concatenation string value like 2013.kbsrc
There is another problem with your structure because kb_work[year] should be an obeject not an array, again the second level of keys need not have the year again.
So the structure can be updated to
var kb_work = {}
kb_work['2014'] = {};
kb_work['2014']['kbid'] = ["46"];
kb_work['2014']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2014']['kbtitle'] = ["Test 5"];
kb_work['2014']['kbmedium'] = ["Oil"];
kb_work['2014']['kbsize'] = ["2x5"];
kb_work['2014']['kbdate'] = ["2014"];
kb_work['2013'] = {};
kb_work['2013']['kbid'] = ["44"];
kb_work['2013']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2013']['kbtitle'] = ["Test 3"];
kb_work['2013']['kbmedium'] = ["Oil"];
kb_work['2013']['kbsize'] = ["2x1"];
kb_work['2013']['kbdate'] = ["2013"];
kb_work['2012'] = {};
kb_work['2012']['kbid'] = ["45"];
kb_work['2012']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2012']['kbtitle'] = ["Test 4"];
kb_work['2012']['kbmedium'] = ["Oil"];
kb_work['2012']['kbsize'] = ["2x3"];
kb_work['2012']['kbdate'] = ["2012"];
then to access it
kb_work[gallery_year]['kbsrc'][currentImg]

Your nesting shows that you think this works differently to how it actually works...
var kb_work = {}
kb_work['2014'] = new Array();
kb_work['2014.kbid'] = ["46"];
Actually results in an object like this: {"2014":[],"2014.kbid":["46"]}
I believe you want this:
var kb_work = {
'2014': [
{ 'kbid': ["46"] }
]
};
Which results in an object like this: {"2014":[{"kbid":["46"]}]}
Now you can access:
kb_work['2014'][0].kbid[0] // 46
And you can pass in the year as a variable containing the string and the 0s can be a variable containing the index.
You can add multiple lines like this:
var kb_work = {
'2014': [
{ 'kbid': ["46"] },
{ 'kbid': ["62"] },
{ 'kbid': ["90"] }
]
};

Related

Javascript Appending to 2-D Array

I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}

How to get value stored in array object in javascript

I m storing values as object which i get dynamically, now i need to retrieve those values, its simple question but i didnt get the answer so i asked here.
for example:
/* Adding values dynamically into array of saveData. */
at first :
id = 1
gettext = 'Y'
text = 'Hello world'
at second :
id = 2
gettext = 'N'
text = 'JavaScript'
etc....
My code:
var saveData = {};
var objterm = {};
objterm["valueID"] = id;
objterm["valueGot"] = gettext;
objterm["text"] = text;
saveData[id] = objterm; // Saving values in array...
How can i retrive a value eg: say, saveData[1] -> gettext, text
// I tried the below to get value as
var obj = _.find(saveData, function(obj) { return obj.id == id }); // did nt get values
From the code you provided both saveData and objterm are simple objects, so if you wanted to retrieve specific data from some specific entry to saveData all you need to do is this:
saveData[id].valueGot
based on
objterm["valueID"] = id;
objterm["valueGot"] = gettext;
objterm["text"] = text;
It is working after adding http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js
For _.find & _.findWhere method.
var saveData = {};
var objterm = {};
objterm["valueID"] = 1;
objterm["valueGot"] = 'Y';
objterm["text"] = 'javascript';
saveData[1] = objterm;
var obj = _.find(saveData, function(obj) { return obj.valueID == 1 });
var obj2 = _.findWhere(saveData, {valueGot: 'Y' });
console.log(obj)
console.log(obj2)
https://jsfiddle.net/anil826/7ay25qwu/

Node.js array instantiation

So, I have been trying for a while now and no luck. Currently I have an associative array as based on PSN profile data:
var PROFILE = {};
PROFILE.profileData = {};
PROFILE.titles = {};
and is used like this further down in the code:
PROFILE.profileData.onlineId = profileData.onlineId;
PROFILE.profileData.region = profileData.region;
PROFILE.titles[title.npCommunicationId] = title; //For looped, can be many
PROFILE.titles[title.npCommunicationId].trophies = {};
PROFILE.titles[title.npCommunicationId].trophies = trophyData.trophies; //any where from 10 - 50+ of these, for looped
Problem is, if I want to have multiple profiles, this doesn't work as it just inserts them in the same profile. I need 'PROFILE' to be an array that has all the above elements at each index.
PROFILEarray[n].profileData = {};
PROFILEarray[n].profileData.onlineId = profileData.onlineId;
PROFILEarray[n].profileData.region = profileData.region;
Something like this is what I need^
But for the above I get this error
Cannot read property 'profileData' of undefined
Once this is complete, it's saved into a file in JSON format to then be used by PHP code I've written to insert into a db.
This is a small snippet of the json output: http://textuploader.com/5zpbk (had to cut, too bit to upload)
you must define PROFILEarray[n] as object. JavaScript objects are containers for named values. You can not set value of undefined
PROFILEarray[n] is undefined in this case. Initialize it as {}(object)
Try this:
var PROFILEarray = [];
for (var n = 0; n < 5; n++) {
PROFILEarray[n] = {};
PROFILEarray[n].profileData = {};
PROFILEarray[n].profileData.onlineId = n;
PROFILEarray[n].profileData.region = 'Region' + n;
}
alert(JSON.stringify(PROFILEarray));

array push method not working properly

I am getting the following error for third line:
Can not set property accountName of Undefined
Can anyone help?
var temp = [];
temp.accountId = newData.Account.Id;
temp.accountType = newData.Account.Type;
temp.accountholder.accountName = newData.Account.Name;
finaloutput.push(temp);
set temp.accountholder in advance.
var temp =[];
temp.accountId = newData.Account.Id;
temp.accountType = newData.Account.Type;
temp.accountholder = {};
temp.accountholder.accountName = newData.Account.Name;
finaloutput.push(temp);

How to use contents of array as variables without using eval()?

I have a list of variables or variable names stored in an array. I want to use them in a loop, but I don't want to have to use eval(). How do I do this? If I store the values in an array with quotes, I have to use eval() on the right side of any equation to render the value. If I store just the variable name, I thought I'd be storing the actual variable, but it's not working right.
$(data.xml).find('Question').each(function(){
var answer_1 = $(this).find("Answers_1").text();
var answer_2 = $(this).find("Answers_2").text();
var answer_3 = $(this).find("Answers_3").text();
var answer_4 = $(this).find("Answers_4").text();
var theID = $(this).find("ID").text();
var theBody = $(this).find("Body").text();
var answerArray = new Array();
answerArray = [answer_1,answer_2,answer_3,answer_4,theID,theBody]
for(x=0;x<=5;x++) {
testme = answerArray[x];
alert("looking for = " + answerArray[x] + ", which is " + testme)
}
});
You can put the values themselves in an array:
var answers = [
$(this).find("Answers_1").text(),
$(this).find("Answers_2").text(),
$(this).find("Answers_3").text(),
$(this).find("Answers_4").text()
];
for(x=0;x<=5;x++) {
alert("looking for = " + x + ", which is " + answers[x])
}
EDIT: Or even
var answers = $(this)
.find("Answers_1, Answers_2, Answers_3, Answers_4")
.map(function() { return $(this).text(); })
.get();
If your answers share a common class, you can change the selector to $(this).find('.AnswerClass').
If you need variable names, you can use an associate array:
var thing = {
a: "Hello",
b: "World"
};
var name = 'a';
alert(thing[name]);
This would make it easier to get the array populated.
var answers = new Array();
$("Answers_1, Answers_2, Answers_3, Answers_4", this).text(function(index, currentText) {
answers[index] = currentText;
});
As others have mentioned, if you can put the variables in an array or an object, you will be able to access them more cleanly.
You can, however, access the variables through the window object:
var one = 1;
var two = 2;
var three = 3;
var varName = "one";
alert(window[varName]); // -> equivalent to: alert(one);
Of course, you can assign the varName variable any way like, including while looping through an array.

Categories

Resources