0

Below a sample version of the code I'm having problems with. I have a dynamic function that I use at some other place in order to dynamically select certain attributes, e.g., as shown here blabla.years.y2011.hello. However, this does not work, and I've found out that the variable 'o' here is not replaced by its actual value, e.g., hello or bye but just stays o (see second listing). How can I dynamically use the value of o in the return line?

for (var o in ["hello", "bye"]) {        
        somevar[o] = {
            "f": function(x) {
                    return x["years"]["y2011"][o];
            }
...

Output of console.log of somevar["hello"]:

function (x) {
                    return x["years"]["y2011"][o];
             }

As you can see, o is not replaced by the value hello or bye but just stays o.

pedjjj
  • 958
  • 3
  • 18
  • 40
  • 1
    BTW, for-in loops are not for-each loops. The `o` is going to be 0 and 1 instead of "hello" and "bye", its not guaranteed to iterate in order and it can also iterate over spurious results if someone modifies Array.prototype. Use normal forloops or a forEach method. – hugomg Jul 06 '14 at 20:48
  • 1
    FYI, your question has nothing to do with JSON. JSON is a data format like XML or CSV. – Felix Kling Jul 06 '14 at 20:51
  • Ah yea, that's because in my original code I use for .. in loop to iterate over keys in a map. – pedjjj Jul 06 '14 at 20:52

0 Answers0