Why this Variable does not pass correctly in JQuery - javascript

I have a simple JQuery Statement...and my question is, why in the world does one of these fail?
Lets assume the variable colorAttribute is color
$(thisCLass).css( "color", '#'+hex ); // Works when written
$(thisCLass).css( colorAttribute, '#'+hex ); // Works with variable
$(thisCLass).css({ "color" : '#'+hex }); // Works when written
$(thisCLass).css({ colorAttribute : '#'+hex }); // Does not Work with variable
Any ideas as to why the one fails?

That's because you can't use a variable to specify a name in an object literal.
An identifier in an object literal can be written with or without quotes, so it won't be interpreted as a variable in either case. The object will end up with the identifier that you specify:
{ "colorAttribute" : '#'+hex }
You can use a variable to set a property in an object, but then you have to create the object first and use the bracket syntax:
var obj = {};
obj[colorAttribute] = '#'+hex;
$(thisCLass).css(obj);

because the second one becomes an object with just one property: "colorAttribute".
you should do this:
myobj = {};
myobj[collorAttribute] = "#"+hex;
$(thisClass).css(myobj);
perhaps you're a python programmer, but javascript is not like that regarding dicts (objects here). it happens often.

Object literals/initializers take identifier keys just for their name, not for any values they may represent as a variable. So...
{ colorAttribute: '#' + hex }
...defines an Object with a key named "colorAttribute".
You'll have to use bracket notation to name a key based on a variable:
var css = {};
css[colorAttribute] = '#' + hex;
$(thisClass).css(css);

It doesn't work because you simply cannot do that in JavaScript. In an object literal, the left side of a property declaration is either a string literal or an identifier. If it's an identifier, then the identifier itself is used as if it were a string literal.
You can create an object however and populate a property from a variable:
var cssProps = {};
cssProps[colorAttribute] = '#' + hex;
$(thisClass).css(cssProps);

You can't declare a javascript object literal with a variable for the property name. A property name in a literal must be the actual property name, not a variable.
Instead, if you want to use a variable in the object form, you'd have to construct the object first and then pass it in:
var obj = {};
obj[colorAttribute] = '#'+hex;
$(thisCLass).css(obj);

When you are doing { colorAttribute : '#'+hex } you are creating a new object with a property named "colorAttribute".
I don't know exactly what you need but you could try
var cssObject = {};
cssObject[colorAttribute] = '#'+hex;
//cssObject[otherAttribute] = 'otherValue';
$(thisCLass).css(cssObject);
Hope this was helpfull.

You need a step before writing what you are trying to do here:
First create a variable:
var color = new Object();
color.colorAttribute = '#'+hex
$(thisCLass).css(color);

Related

Complex use of function parameter in javascript

function me(a, b) {
function he(c, d) {
if(!a[c]) {
}
}
}
Please someone explain 'if(!a[c])' for me.
why this square bracket is used here in [c] though it is a parameter. it is not an array obviously.
what does if(!a[c]) make sense? how two parameters are used like this?
There is nothing special about that code.
It is saying, in English, If the property c of a is falsey, then the condition is true.
In JavaScript, bracket notation can be used to access properties of an object or members of an array.
For example, someArray[5] will access the 6th member of the array, while someObject['someProp'] will access someProp of the object someObject.
The argument a is likely an object. The syntax:
if (!a[c])
Checks to see if the property in the variable c on the a object does not have a truthy value. This could be if it was null, false, undefined or any other falsey value.
The bracket notation can be used with property names. So, if you have an object like this:
var x = { name: "John"};
Then, you can access that property like in any of these ways:
x.name
x["name"];
// Or, if the property name is in a variable
var prop = "name";
x[prop]
Your example is using a version of the last of the above three options when the property name is in another Javascript variable.
In javascript, properties can be accessed dynamically using the square-bracket syntax.
Consider the following:
var person = {name:'Sarah'};
console.log(person.name); // logs 'Sarah';
Sometimes, you might want to dynamically access properties of an object, using a variable that holds the name of the property you want to access. The above example could also be written like this:
var person = {name:'Sarah'};
var prop = 'name';
console.log(person[prop]); // logs 'Sarah';

Using a functions argument to find and objects key value pair?

I'm trying to find a key value pair value but i want to pass the key in as an argument but it isn't seeming to work.
function drawPieChart(){
var findData = function(variable){
return dailyLog.find({createdBy: Meteor.user().username}, {fields: {variable: 1}}).fetch()[0].variable;
};
var data = [
{
value: findData(adherence),
color: "#CBDDE7"
}...
I want variable to be passed in twice, once to sort and other to find the value but it is actually looking for the key value pair "variable" which obviously doesn't exist.
How do i make it be seen as the argument?
There are two aspects to this:
Creating the fields object with a property whose name is the value of variable rather than the literal name variable, and
Accessing the resulting field based on the value of the variable (rather than the literal name variable)
Dealing with #2 first because it's easier: In JavaScript, you can access a property on an object either using dot notation and a property name literal (obj.foo), or using brackets notation and a property name string* (obj["foo"]). In the latter case, the string can be the result of any expression, including a variable lookup. So if variable contains "foo", then obj[variable] will get or set the foo property on obj.
Back to #1: For now, you have to create the object you're going to pass as fields first and then assign the property value via brackets notation rather than in an object initializer:
var fields = {};
fields[variable] = 1;
If variable contains "foo", then fields[variable] = 1 sets the foo property on fields to 1.
So putting that all together:
var findData = function(variable){
var fields = {};
fields[variable] = 1;
return dailyLog.find({createdBy: Meteor.user().username}, {fields: fields}).fetch()[0][variable];
// Note ------------------------------------------------------------------------------^--------^
};
In the next version of JavaScript, ECMAScript6 (aka ES6), you'll be able to do #1 with a "computed property name" in the object initializer (and still retrieve it with brackets notation). Perhaps unsurprisingly, computed property names use...brackets!
// ES6 only!!
var findData = function(variable){
return dailyLog.find({createdBy: Meteor.user().username}, {fields: {[variable]: 1}}).fetch()[0].[variable];
// Note ------------------------------------------------------------^--------^ --- and ---------^--------^
};
* Side note: In ES6, brackets notation can be used with things called Symbols as well as strings. It's not relevant to your question, but I said "string" above, and soon that won't be true, so...

Use key's value as key in key-value pair in Javascript

How can you use the value of a key-value pair as the key in a different key-value pair in javascript?
I'd like to do the following:
var gizmos = {gizmo1: "G1"};
var things = {gizmos.gizmo1: "T1"};
So that things essentially equals:
var things = {"G1": "T1"};
Like this:
var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1] = "T1";
There's no way to do it as part of the object initializer (aka object "literal"), you have to do it after.
The reason it works is that in JavaScript, you can access (get or set) a property on an object in two ways: Either using dotted notation and a literal, e.g. foo.bar, or using bracketed notation and a string, e.g. foo["bar"]. In the latter case, the string doesn't have to be a string literal, it can be the result of any expression (including, in this case, a property lookup on another object).
Side Note: If you change gizmos.gizmo1 after you do the things[gizmos.gizmo1] = "T1"; line, it does not change the name of the property on things. There's no enduring link, because the value of gizmos.gizmo1 was used to determine the property name during the things[gizmos.gizmo1] = "T1"; line (just like it is in any other expression).
var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1]="T1";
To get the value for a given key on an object use object["key"] or object.key

How to set a JSON array key on array.push on JavaScript

I'm making some JS code, where I need to set a variable as a key in a JSON array with Javascript array.push():
var test = 'dd'+questNumb;
window.voiceTestJSON.push({test:{"title":""}, "content":{"date":""}});
Where questNumb is another variable. When doing that code, the part where I just write the test variable it just becomes to the key "test", so I have no idea of getting this to wok. How could it be? Thanks!
If you want variables as keys, you need brackets:
var object = {};
object['dd'+questNumb] = {"title":""};
object["content"] = {"date":""}; //Or object.content, but I used brackets for consistency
window.voiceTestJSON.push(object);
You'd need to do something like this:
var test = "dd" + questNumb,
obj = {content: {date: ""}};
// Add the attribute under the key specified by the 'test' var
obj[test] = {title: ""};
// Put into the Array
window.voiceTestJSON.push(obj);
(First of all, you don't have a JSON array, you have a JavaScript object. JSON is a string representation of data with a syntax that looks like JavaScript's object literal syntax.)
Unfortunately when you use JavaScript's object literal syntax to create an object you can not use variables to set dynamic property names. You have to create the object first and then add the properties using the obj[propName] syntax:
var test = "dd" + questNumb,
myObj = { "content" : {"date":""} };
myObj[test] = {"title" : ""};
window.voiceTestJSON.push(myObj);
{test:{"title":""}, "content":{"date":""}}
this is a JS object. So you are pushing an object into the voiceTestJSON array.
Unlike within JSON, JS Object property names can be written with or without quotes.
What you want to do can be achieved like this:
var test = 'dd'+questNumb;
var newObject = {"content":{"date":""}}; //this part does not need a variable property name
newObject[test] = {"title":""};
This way you are setting the property with the name contained in test to {"title":""}.

how to get the value 'dynamically' from an associative array in javascript?

i am trying to get a value from a key stored on a string variable proyNombre, but whenever i call it via the common method "myAssociativeArray.MyKey", it gets the variable 'proyNombre' as the key, instead of getting its value and passing it as a key.
proyectos.each(function(index){
var proyNombre = this.value;
if(!(proyNombre in myArray)){ // whenever the variable is undefined, define it
myArray[proyNombre] = horas[index].value-0 + minutos[index].value/60;
}
else{
console.log(myArray.proyNombre); //This doesnt work, it tries to give me the value for the key 'proyNombre' instead of looking for the proyNombre variable
console.log(myArray.this.value); //doesnt work either
}
});
Try:
console.log(myArray[proyNombre]);
myArray is actually an object in javascript. You can access object properties with object.propertyName or, object['propertyName']. If your variable proyNombre contained the name of a property (which it does) you can use the second form, like I did above. object.proyNombre is invalid - proyNombre is a variable. You can't do for example:
var myObject = {};
myObject.test = 'test string';
var s = 'test';
console.log(myObject.s); // wrong!!
but you could then do:
console.log(myObject.test);
console.log(myObject['test']);
console.log(myObject[s]);
You need to use the same syntax you used to set the value:
console.log(myArray[proyNombre]);
Simply access the value with myArray[proyNombre].
You're doing it right in the assignment: myArray[proyNombre]. You can use the same method to retrieve the variable.
If you change:
console.log(myArray.proyNombre);
console.log(myArray.this.value);
to
console.log(myArray[proyNombre]);
console.log(myArray[this.value]);
You should get the same value (the value for the key represented by the variable proyNombre) logged twice.
It's true that Javascript doesn't have associative arrays but objects in Javascript can be treated like associative arrays when accessing their members.

Categories