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']
Related
This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?
Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation
As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I have an object and a few variables I'd like nested inside the variable but for some reason I can only ever get the first nest. Anything after that gives me an error stating that it couldn't read because it was undefined:
var date = 10;
var timestamp = 100;
Que[date] = {timestamp:{"test":"test"}};//this returns {10:{"timestamp":{"test":"test"}}}; for some reason
Que[date][timestamp] = {"test":"test"}; //errors saying, cannot read '100' undefined
console.log(Que);
I'm not sure why this is happening and I'd really like to resolve it with simple means. Btw the Que variable is global inside another script and predeterminietly contains {"10":{"24":{"1":"test"}}}; which is likely why the date variable does work but the timestamp variable doesn't. Any suggestions?
EDIT:
date, and timestamp are both declared outside of the object, however i wish to use them as key's inside of the object..
uppon reading the mod suggested post and implementing what it contained, i ended up with another error
Que = {[date]:{[timestamp]:{"test":"test"}}};//this results in an unexpectd token error located at the [ before date
I think there are more questions to be asked based off of your code snippet, but in your example timesheet is not defined, you can reference the key inside your JSON by using
Que[date]["timesheet"]
To access the object inside. The key that you're looking up with the [] notation should be a string.
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Problem with example:
Variable name: var product5519 = 10;
I can get this name in the form of a String i.e
var str = "product5519"
Is there any way to convert it into variable name so that i can use the value assigned to
product5519
I know one way to solve this problem i.e using eval(str)
If there is any another way to solve it please tell?
Once you are certain creating a global variable was the Right Thing to do, you can add your variable to the window object, like so:
window[str] = 42;
This works because variable lookups end up trying the window object if the variable was not defined in an inner scope.
It's a bit hacky but if you wanted to make a global variable you could do:
var str = "product5519";
window[str] = value;
You could then access the variable like:
window[str];
window.str;
str; // Assuming that there is no local variable already named "str"
you could do something like:
window['product5519'] = 'value'
it may be better to have an array of products, depending on the situation ofc.
You can use an associative array:
var variables = [];
variables['product5519'] = 10;
console.log(variables['product5519']);
This question already has answers here:
Variable name as a string in Javascript
(20 answers)
Closed 2 years ago.
I am trying to write a convenience wrapper for console.log, and I would like to print any variables passed in along with their contents.
Can I turn a variable name into a string in js?
Assuming you want something like this:
function Log(data)
{
console.log(input variable name, data);
}
Then I don't think it is possible:
For convenience.. you could do something like
console.log({ "your variable name": your variable});
Which turns the input to an object that does contain the variable name you want to log.
A little more typing, but perhaps makes the console output more readable.
There is a possibility. And here is how
var passed_variable = '65'; // The actual variable
var varname = 'passed_variable'; // The name of the variable in another variable
Now, pass the varname around but not the actual variable. When you need to the value of the variable you can simply do :
console.log(varname, ' : ', window[varname]); // Outputs, passed_variable : 65
I hope you find a way not to use this. :)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript object, access variable property name?
I am messing around with JS, learning a stuff and I am wondering about something...
Say you have a function aFunc(), and you accept a string aFunc(val). The value is user defined and is then used to modify the CSS of an element.
For Example:
function aFunc(val){
document.getElementById('something').style.val = 'red';
}
Say the user entered borderColor, it would somehow refrence borderColor where val is. I do not know how or if this is possible.
EDIT:
Please no eval() :)
Just use this as a base: JSBIN- Demo on a Div
var type = prompt("style");
var value = prompt("value");
document.body.style[type] = value;
Every object in JavaScript has a method called hasOwnProperty which takes a string value and will return a Boolean value.
var myObj = {
name: "Josh"
};
myObj.hasOwnProperty("name") === true; //This is true
You can use that to test for the presence of a particular property and then use the method stated in Akhil Sekharan's answer to access that property.