Use a variable inside a dictionary (associative array) in javascript [duplicate] - javascript

This question already has answers here:
Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]
(7 answers)
Closed 8 years ago.
I have this particular script which uses a javascript dictonary
var z= 'Bingo';
var fruit={ 'Bingo' :1};
var fruit2={ z :1};
alert(fruit[z]);
alert(fruit2[z]);
alert(fruit2['z']);
The first alert gives the expected value 1. However, the second alert gives the alert value as "undefined" and third alert gives the output as 1. Is there a way to use a variable inside a dictionary, ie. can we specify the javascript interpreter to read z as a variable rather than as string 'z'?
Thanks!

Yes, you can do this easily, but not inside an object literal. Property names in object literals are taken literally. They are not variable names. JavaScript quotes them implicitly if you don't quote them.
For example, these two object literals are the same:
{ a: 1 }
{ 'a': 1 }
To use a variable, you need to use [] notation outside an object literal:
var z = 'Bingo';
var fruit2 = {};
fruit2[z] = 1;

Related

Using Function Variable to Retrieve Object Literal Value [duplicate]

This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 6 years ago.
I have a function that converts an object literal response data into an array:
From: [{"_id":"1","rating":7},{"_id":"2","rating":3}]
To: [7,3]
function createArray(fieldVar, responseData) {
var newArray = responseData.map(function(data) {
return data.fieldVar // fails here because I am trying to use the fieldVar variable
});
return newArray
};
I call the function like this:
createArray('rating',response.rating_x)
This fails because of the data.fieldVar If I hardcode the call to data.rating it works correctly.
How do I pass in the 'rating' or any other name on the function call?
Try it with brackets
function createArray(fieldVar, responseData) {
var newArray = responseData.map(function(data) {
return data[fieldVar] // access with brackets
});
return newArray
};
When using the dot-notation, the property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), not starting with a number. When you're using variables, you need to use bracket notation, else data.fieldVar would point to the property 'fieldVar' which probably doesn't exist. This is because the variable that you intended to access is not evaluated, but instead treated as a normal "string".
More informations on MDN: Property accessors

how to use arry element as array name in Javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
im practicing javascript and i have arrays (more than 10) which have strings in it
var p = ["one","two","three","four"];
var q = [//somthing here]
and another array which is created by a function which select n store some array names for further actions
var m = ["p","q","r","s"];
how can i use element of array m as the varable/array name like:
<button onclick="testArrays(dest, m[0])">desti</button>
must have to work like this
<button onclick="testArrays(dest, p)">desti</button>
all i want to say that how can i use m[0] as a variable
im not using objects
As a variable where? If it's a property of an object you can use object[m[0]]
And if it's on the global scope you can use the window object window[m[0]]. If it's a variable inside a function you should rethink your approach. There is a way that starts with e and ends with val and you should never, ever use it.

Using String to get JSON Property [duplicate]

This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']

Adding custom variables to an object [duplicate]

This question already has answers here:
How to convert string as object's field name in javascript
(5 answers)
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
Suppose I have an object obj which has some variables in it. What I want to do is to add a new variable which has a name i gave as a parameter.
For example:
var obj=
{
number:8
}
function AddField(field_name,obj)
{
//some magical code here
}
If I call
AddField('name',obj);
i want to be able to do
obj.name='Apple'
after calling this function.
Any ideas?
Use square brackets notation:
obj[field_name] = value;
REF: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId
Use the bracket notation:
obj[field_name] = void 0;
This creates a new property with an undefined value.
If obj is already defined, you can just do obj.field_name = null or obj["field_name"] = null.
I wouldn't set any value to undefined even though the language allows for that, simply for a semantic issue: undefined means "this property/variable has not been defined" and null means "this property/variable has no value".

How to access a dynamic property: objectName.{variable} [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
jquery dynamic id
(4 answers)
Closed 8 years ago.
i need to access
objectName.myID
but the "myID" part is dynamically generated..
how do i do this?
i tried
this['objectName.'+ variable]
i'd hate to use eval...
ps
this happens in a function (local scope) by the way..
You can access Object properties in two ways:
o.propertyname
//or
o.["propertyname"]
When using the bracket notation you have to put the propertyname in quotes or else it will be interpreted as a variable name (which in your case is exactly what you want). So in your case where you have stored the name of the property as a string, the way to go would be:
var variable = "propertyname";
o[variable];
/* /\ variable is replace with it's string representation "propertyname" */
You can even call methods this way:
var o = {};
var functionname = 'toString';
o[functionname]();
You can mix both notations, your example would look like:
var obj = 'objectName';
var prop = 'myID';
this[obj][prop]
// or this is possible too:
this.objectName[prop]
Assuming propertyName is the name of a variable holding the name of the property, for example 'myId', then you can use.
objectName[propertyName]
More details in the MDN : Working with objects

Categories