0

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
5
  • 1
    You shouldn't do this. Commented Oct 31, 2017 at 23:10
  • OK ... but what if I need to? Commented 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? Commented Oct 31, 2017 at 23:17
  • Possible duplicate of How to use a string as a variable name in Javascript? Commented 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! ;) Commented Oct 31, 2017 at 23:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Worked for me! Thanks Matt!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.