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!

Martin Carre
  • 1,157
  • 4
  • 20
  • 42
  • 1
    You shouldn't do this. – ATOzTOA Oct 31 '17 at 23:10
  • OK ... but what if I need to? – Martin Carre Oct 31 '17 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 Oct 31 '17 at 23:17
  • Possible duplicate of [How to use a string as a variable name in Javascript?](https://stackoverflow.com/questions/6160146/how-to-use-a-string-as-a-variable-name-in-javascript) – Matt Oct 31 '17 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 Oct 31 '17 at 23:25

1 Answers1

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
Matt
  • 68,711
  • 7
  • 155
  • 158