How to assign a JSON value to a var in JavaScript? - javascript

I would like to assign a JSON value to var, however i get the following error.
Error message
var a = { myData.results[count].category[count] }

Maybe a syntax error, either make it a property of an object:
var a = { prop: myData.results[count].category[count] };
Or just the value:
var a = myData.results[count].category[count];

Related

Can not assign variable because type is null?

canvas.getActiveObject().type returns the type of the currently active element in the canvas.
var type = canvas.getActiveObject().type;
if(type){
console.log(type);
}
But when no element is active, I get TypeError, which of course happens because no element is active so there is nothing to getActiveObject from.
TypeError: canvas.getActiveObject(...) is null
Why can't I assign a variable when the activeObject is null?
Same error happens, when I try
var type = '';
if(canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
canvas.getActiveObject() is returning null.
That means that canvas.getActiveObject().type is the same as null.type.
Referencing any member of null will throw an exception.
You can solve this any number of ways
Three lines of code:
let type = '';
if(canvas.getActiveObject()) {
type = canvas.getActiveObject().type;
}
Or a one-liner:
let type = canvas.getActiveObject()
? canvas.getActiveObject().type
: '';
Or a more compact one-liner:
let type = (canvas.getActiveObject() || { type: ''}).type;
You can't access a null value like an object, I think you should safely access the value like.
var type = '';
if(canvas.getActiveObject() && canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
It looks like you're trying to access the property type returned by the function getActiveObject(), but since the function returns null, accessing the type property is throwing an error. What you need to do instead is check the return value of getActiveObject() before trying to access any of its members.
The snippet below, which is based on your code, instead checks that the active object returned is not null before attempting to access the members that reside within it.
var activeObject = canvas.getActiveObject();
if (activeObject) {
console.log(activeObject.type);
}

Why can't I declare an object from array?

a simple example, Why does this give an error?
var zipped = [[0,1,2]];
var extracted = {};
var i = 0;
extracted[zipped[i][0]] = { zipped[i][1]: zipped[i][2] }
>>>Uncaught SyntaxError: Unexpected token [(…)
when this is perfectly fine?
extracted[0] = { 1: 2 }
Because Javascript object literal syntax does not allow expressions in key parts. Keys are always literal. That's why you can write this:
{ foo: 'bar' }
And foo is not taken as a variable.
For variable keys, you always have to use this pattern:
var obj = {};
obj[varKey] = value;
That is invalid syntax. A number is syntactically allowed in an object literal. Arbitrary expressions are not.
Instead, you need to create the object, then set the attribute.
var obj = extracted[zipped[i][0]] = {};
obj[ zipped[i][1] ] = zipped[i][2];

jQuery param dynamic object name

why can't i have a variable in an object? I get an error like:
"Uncaught SyntaxError: Unexpected token this"
My code is like this.
$("#search_options input:checkbox").on('click', function() {
var params = {
$(this).attr('name') : $(this).val(),
};
var str = jQuery.param(params);
});
I'm sure that $(this) is working because I tried to console.log it outside the params object then i is working.
Object literals cannot have variable property names. You'll have to assign the property like so:
...
var params = {};
params[$(this).attr('name')] = $(this).val();
var str = jQuery.param(params);
If you want to use value of a variable as a property name, you must use this syntax:
var params = {}
params[$(this).attr('name')] = $(this).val();
The literal notation, that you're trying to use, expects property name to be a valid JavaScript identifier.

How to set a Javascript object values dynamically?

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

Using variable name in JS object?

I defined a variable which will get user's input:
var input = USER_INPUT;
then, I create an object which will use this input as an variable name inside the object:
var obj = { input: Car.newCar(...)}
Then, I try to access the obj[input], but it returns to me undefined. Is it so that in javascript, I can not use variable as an object's variable name?
If I would like to define a object which has vary variable name and variable value, how can I do?
So I guess you want the store the input under a key named after the input itself.
You can assign the value returned by Car.newCar() by using the [] method:
var input = "some text";
var obj = {};
obj[input] = Car.newCar();
Sorry changed my answer after re-reading the question
var USER_INPUT = 'something';
var obj = {};
obj[USER_INPUT] = 'value';
obj.something ; //# => value
obj['something'] ; //# => value
obj[USER_INPUT]; //# => value

Categories