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
Related
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...
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);
Crockford writes in http://javascript.crockford.com/survey.html:
"There are two ways to make a new array:
var myArray = [];
var myArray = new Array();"
So I'm confused by these two lines in some AJAX code I am reading:
var obj={}; // obj is an Object object (i.e. a hash table)
obj[4] = 'x'; // now obj is suddenly an Array object via an integer key?
In JavaScript are an object and an array really just the same thing, but with a variant on the key type?
In other words, is this the same as in php where we can use either a name (string) or an integer for a hash key?
I've Googled for an answer on this but can't seem to nail down an article which discusses this issue.
One possibility that comes to mind is that perhaps the first line is syntactic lint because the 2nd line overwrites the previous definition of obj as it creates a new Array object.
it does not become an array, it is simply an Object with a '4' property, like this:
var obj = {
'4': 'x'
};
it is just converted to a string when used as a property like obj['4'] = 'x';
Everything but primitive datatypes is an object in JavaScript. Objects can have a properties and there are two ways to access object properties:
Dot notation, foo.bar, which you can use as long as the property name is a valid identifier.
Bracket notation, foo['bar'] which you have to use if the key is not a valid identifier [spec]. For example, if it is a number, or contains a space or you have a variable with the name.
Hence, bracket notation is not a characteristic of arrays and if you see it, it does not mean the value is an array. It is simple one of two ways of accessing properties.
The elements of an array are just properties with numeric keys. Arrays are built on top of objects and implement some additional methods which treat these numeric properties in a special way. For example the .length property is automatically updated when you add new elements. But ultimately they are just normal properties.
In your example you have a simple object. You have to access the property with obj[4] or obj['4'] because obj.4 is invalid since 4 is not a valid identifier (basically everything that you can use as variable name is a valid identifier. var 4 = 'foo'; is invalid).
And since arrays are just objects, if you could use numbers as identifiers, you were also able to access an element with arr.4.
As far as I know, no, an object can't be coerced into an array. But, it can look and act like an array, and that's what's happening here. Numbers, and anything else that can be coerced to a string, are perfectly valid property names for Javascript objects, so
obj[4] = 1;
obj['spam'] = 2;
are both valid ways of setting a property on the object. That doesn't make the object an array. An Array is a special class of object with specific methods (.slice(), .concat(), etc) and a length property that's kept up to date with the number of items in the array.
Yes
Javascript Array is very different from tradition array, you can think of it as object.
var array = [1,2,3] is equivalent to var object = {'0' : 1, '1' : 2, '2' : 3}
except array inherited from Array.prototype and object inherited from Object.prototype, where Array.prototype will contain method such as length.
Javascript is a loosely-typed, prototype-based language. Even primitive types like a boolean can be treated like an object (though you aren't going to get far). Almost everything in javascript is, at root, an object.
Understanding this, an array IS an object. You can arbitrarily add properties to any object:
var xml = new XMLHttpRequest();
xml[4] = 'x';
console.log(xml);
That object is still an instance of XMLHttpRequest. It now has a property labeled 4 with a value of x. You can treat anything like this -- even a function:
var test_func = function () {
alert('woah!');
}
test_func[4] = 'x';
console.log(test_func[4]);
The take-away here is that the obj[key] = value notation is NOT indicative of an "array" type, like it is in languages such as PHP. Rather, it is an alternate way to access properties of any object, and is equivalent to obj.key = value (you can't use obj.4 = 'x', though, that's invalid syntax). The other take-away is that any object in javascript can be modified or used in pretty much any way. You shouldn't misuse objects, but you can
Check it out here: http://jsfiddle.net/w2AqJ/
Documentation
Array on MDN - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
Javascript "associative arrays" considered harmful by Andrew Dupont - http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
Doing so
var x = new Array();
x['length']=5;
will make x an array of 5 undefined items, but I actually want to have the value '5' stored at key 'length'.
Is that possible?
In javascript arrays do not have keys. You are looking for objects:
var x = {}
x.length = 5;
I have to parse a file containing many words and store the number of occurences of each word
Use an object, and make the words the keys. You aren't storing sequential / ordered data, so you shouldn't use an array.
var word_count = {};
for (var i; i < words.length; i++) {
var word = words[i];
if (word_count[word]) {
word_count[word]++;
} else {
word_count[word] = 1;
}
If you want to do this you'd be better off creating an object rather than an array. This should give you what you want.
var x = {};
x['length'] = 5;
You can call methods on a javascript object using two different syntaxes. The familiar 'dot' syntax with parens to invoke the method, and the square bracket syntax. You can 'call' a method on a javascript object using the syntax myObj["methodname"](args). This is handy when you want to construct the method name dynamically using strings. Remember, objects in javascript are very much like a hash table (dictionary) where keys denote property and function names. If a key's value holds a function, it can be invoked (using parentheses).
In your example, Array has a method called 'length'. You are inadvertently calling its setter (which sets the length of the array to empty values, i.e., undefined).
Putting that all aside, you really do want a hash (associative array) in this case. An array is an offset indexed data structure.
A simple object literal like myObj = {} will suffice to give you hash semantics (again, objects in javascript are already like hashes) and you can then call myObj.whatever = "some value"
You could use objects instead of arrays to store your data. But if you need to use Arrays (you might need to use their functionality), You could cripple the words and store them as array keys.
Use some kind of simple rule to follow to bypass all the possible keywords. For example prefix all your array keys with a "_" character. This way you could always restore the original words from the keys, by simply removing their first character, and you are sure you are not referencing any specific property of the Array objects (like the length property).
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":""}.