0

How to loop through this data: (I have no control over format)

{"rowCount":3,"1":{"K":"2009","V":"Some Data"},"2":{"K":"2010","V":"More Data"}}

Above is a console.log(results) and results is a string

var r = JSON.parse(results);
var t;

for(var i=1;i<=r.rowCount;i++) {
    t=r[i].V;
    tableData.push(     
        {title:t, year:'2009', hasChild:true, color: '#000'}
    );                                      
}               

Error: TypeError: 'undefined' is not an object (evaluating 'r[i].V')

I cannot get it to evaluate the variable i. What am I doing wrong? Thanks

UPDATE

The incoming data had a bad rowcount causing the error. The accepted answer however is correct... just user error on my part not catching the bad incoming data. Had I put a console.log inside the loop I would have realized the error was actually happening after two successful loops. oops

1
  • @Ja͢ck how did you get that underline to your name? Commented Nov 27, 2014 at 14:29

1 Answer 1

3
  • I assume r.rowCount should be j.rowCount.

  • Ideally you should also initialise the i variable if you haven't already (i.e. with the var keyword).

  • (I've also moved the var t declaration outside the loop, to make it clear that it's the same t throughout and you're just changing its value. You shouldn't redeclare it with var each time – although I doubt this affects the output.)


var j = {"rowCount":2,"1":{"K":"name","V":"john"},"2":{"K":"name","V":"sue"}};  
var t;

for (var i = 1; i <= j.rowCount; i++) {
    t = j[i].V;
    console.log(t);
} 

Working demo – JSFiddle

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I updated question, and tried exactly what you have and it still didn't work. The problem was traced back to what JSON.parse() was returning. Strange.
@sday JSON.parse parses from a string representation of an object (i.e. JSON) to a native Javascript object. What you are giving it there is already a Javascript object, why is why you're getting an error – you can't parse something that's already in parsed form.
Thanks again. var results was coming in as a string. going between my code and jsfiddle was excellent. I had my code wrapped in try/catch and "actual" data was a bit longer and didn't catch the fact that the incoming data has rowcount higher than actual elements in data. So try catch would fail out with my list never populated making me think the error was on element 1 when it was actually once it went outside of array bounds so to speak. USER ERROR Thanks again!

Your Answer

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.