String variable as key of an object


#1

I have an object and an array of keys for the object

object = { “12”: { …} , “34”: {…}, “45”: {…} }
stringVar = “34”;

I am trying to retrieve the subject based on the key in the string variable

var subobj = object[stringVar];
console.log(subobj) ;

but it returns undefined. what am I doing wrong ?

I am new to meteor and js, please excuse my poor knowledge


#2

You must have something else going on, as the snippet of code you posted is fine. Try it out in the console in your browser. Are you 100% sure that the variable you’re trying to use as the key actually matches a key in your object?


#3
console.log('object=', object);
console.log('keys=', Object.keys(object));
console.log('stringVar=', stringVar, typeof stringVar);
console.log('value=', object[stringVar]);

It always helps to just put some debug log statements in there and see what you get, see what values all your variables actually have. I often wish that there was a way to do that without writing a gigantic number of console.log statements, but hey, that works, even if it’s not very efficient to write.


#4

Can’t you do that and many more with a debugger ?


#5

You can. I just find it annoying / inconvenient to have to manually set a breakpoint, and navigate around to find all the variables that I’m looking for. Granted, in this simple case setting 1 breakpoint and looking at the variables in the debug panel is probably easiest & fastest. But as soon as you have multiple places in the code you’re interested in and multiple executions/calls of those code points then you have to 1) press a lot of buttons (resume, resume, resume, step, resume, …) and 2) keep the sequence of values that you’ve seen in mind instead of seeing it all laid out in front of you at once.

If a debugger could produce a kind of “flow diagram” that shows me how all the values that I’m interested in have changed during execution, then I would use that debugger. But then it probably wouldn’t be called a “debugger” any more but something more like an “on-demand runtime state flow visualizer” or so :wink:

This was a bit off-topic, but hopefully still of interest to those just getting started (or close) with development.


#6

Thank you all, for suggestions on troubleshooting

Here’s what was happening
Instead of a string, I did console.log on strVal. it showed I was getting a string object (not sure what this is ) like
String {0: “2”, 1: “4”, length: 2, [[PrimitiveValue]]: “24”}
I was doing a JSON.parse on it to get the sting value, which was causing the issue.
this string object was not working with dot notation, but worked with square brackets [ ] to get the right subobject.