Javascript object undefined issue - javascript

I'm a little stumped here. Can someone tell me why this works:
var selectedAttrs = {"mattress_size_variation":{"displayName":"Mattress Size","value":"King","displayValue":"King"},"mattress_feel_variation":{"displayName":"Mattress Feel","value":"Soft","displayValue":"Soft"}};
var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();
//Returns "King"
But this does not and throws an error?
var selectedAttrs = {"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}};
var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();
TypeError: Cannot read property "value" from undefined
What is the difference and how should I get the value from the last one? I'm assuming I need to do some sort of check since one works and the other does not.

There's a untrimmed space in your second JSON so you have to access that property using square brackets:
selectedAttributes['mattress_size_variation ']
var selectedAttrs = '{"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}}'
var selectedAttributes = JSON.parse(selectedAttrs);
console.log(selectedAttributes['mattress_size_variation '].value);

Related

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

Json Javascript String Syntax error when parsing an array

I have the following code javascript code
var tasksPlayed = [];
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);
this gives an error
SyntaxError: JSON.parse
Im not sure why, if I do a .toSource() on the objects I get
keyValue:"[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true]"})
Any ideas where I might be going wrong
I don't get this error when I run the code, but the thing with the null values is that tasksPlayed is an array, so when you set tasksPlayed[90] = true;, then it automatically fills all positions from 0 to 89 with null. Try using a plain object instead of an array:
var tasksPlayed = {};
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);

parsing a JSON fails with missing element in javascript

I am trying to use Youtube's Gdata JSON response in javascript. My code iterates through the playlist and extract the item data.but for few videos the rating is not there which throws
"TypeError: item.gd$rating is undefined"
is there a way to check before accessing the element.
this is the code with with i fetch the json response.
var avgrating = item['gd$rating']['average'];
var maxrating = item['gd$rating']['max'];
var minrating = item['gd$rating']['min'];
var numRaters = item['gd$rating']['numRaters'];
One way you can just do to avoid error is
var rating = item['gd$rating'] || {}; // If it is undefined default it to empty object
var avgrating = rating['average']; //now if it is not present it will just give undefoned as value
var maxrating = irating['max'];
var minrating = rating['min'];
var numRaters = rating['numRaters'];
Or explicitly check:
var rating = item['gd$rating'], avgrating, maxrating;
if(rating)
{
avgrating = rating['average'];
maxrating =rating['max'];
...
}
Note that in the if condition we are checking for truthiness of the expression so, anything other than undefined, null, "", false, 0 will be treated as true and will go into the condition. But here you are sure that it will be either an object or nothing so you can rely on this check.

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

Javascript Newb : How do I instantiate a var as "blah.1" and "blah.2"?

I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );

Categories

Resources