I'm trying to have a variable (plain text) used to reference another variable (Object) and then call on it to get information from the referenced variable (Object). In concrete:
var bar1 = {
p: 1,
v: 0.1,
sn: 1509475095
};
var bar2 = {
p: 2,
v: 0.2,
sn: 1509475095
};
foo = 'bar1';
console.log(bar1.p); // Prints 1
console.log(foo); // Prints 'bar1'
console.log(foo.p); // Want this to somehow print 1
Any ideas? I think this is related with the fact that foo in my example is a String... but not sure how to manipulate the String to be able to get the reference.
Thanks in advance!
asked Oct 31, 2017 at 23:05
Martin Carre
1,2594 gold badges24 silver badges47 bronze badges
-
1You shouldn't do this.ATOzTOA– ATOzTOA2017年10月31日 23:10:20 +00:00Commented Oct 31, 2017 at 23:10
-
OK ... but what if I need to?Martin Carre– Martin Carre2017年10月31日 23:12:19 +00:00Commented Oct 31, 2017 at 23:12
-
1@Ardzii then you should take a step back and reconsider your design. Shouldn't these variables be keys in a map or a POJO?JB Nizet– JB Nizet2017年10月31日 23:17:11 +00:00Commented Oct 31, 2017 at 23:17
-
Possible duplicate of How to use a string as a variable name in Javascript?Matt– Matt2017年10月31日 23:24:33 +00:00Commented Oct 31, 2017 at 23:24
-
Hey JB! You're right and actually the suggestion given by Matt below fits perfectly my design! Thanks for your help! Plus I know now what a POJO is so thanks for that! ;)Martin Carre– Martin Carre2017年10月31日 23:25:17 +00:00Commented Oct 31, 2017 at 23:25
1 Answer 1
Create an object to hold the variables so that you can reference them via a string.
var bars = {
bar1: {
p: 1,
v: 0.1,
sn: 1509475095
},
bar2: {
p: 2,
v: 0.2,
sn: 1509475095
},
};
foo = 'bar1';
console.log(bars.bar1.p); // Prints 1
console.log(foo); // Prints 'bar1'
console.log(bars[foo].p); // Prints 1
answered Oct 31, 2017 at 23:18
Matt
75.8k11 gold badges172 silver badges167 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Martin Carre
Worked for me! Thanks Matt!
lang-js