KrankyCode
KrankyCode

Reputation: 451

Fetching JSON data on second iteration is throwing an error

There are two rows of JSON data stored as string

First Row - {"content":[{"title":"Test1","desc":"Team1","image":"http://team.jpg"}],"leftnav":[{"navtitle":"Nav One","navdesc":"One Link","navimage":"http://plan.jpg"}]} 

Second Row - {"content":[{"title":"Test2","desc":"Team2","image":"http://group.jpg"}],"leftnav":[{"navtitle":"Nav Two","navdesc":"Two Link","navimage":"http://graph.jpg"}]} 

Using each function i am iterating trough each row and trying to access the data, as below

Where "resultRegionArr" is the object of objects

$(resultRegionArr).each(function(x){

var str = resultRegionArr[x].testdata;// str is assigned each row at a time
var finalobj = JSON.parse(str); // String is been converted to objects
alert(finalobj.leftnav[x].navtitle);

}

for first time iteration i.e finalobj.leftnav[0].navtitle I am able to get the correct result - Nav One

for second time iteration i.e finalobj.leftnav[1].navtitle I am getting an error finalobj.leftnav[x] is not defined.

Thanks in advance

Upvotes: 0

Views: 114

Answers (3)

som
som

Reputation: 4656

var str = resultRegionArr[x].testdata;// str is assigned each row at a time
var finalobj = JSON.parse(str); // String is been converted to objects
alert(finalobj.leftnav[0].navtitle);

Try this.

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

This code does not make sense. Using a foreach should return the value as first argument in the callback function. You can than use that value to do stuff. Second, using the x value in the last line seems weird because that is used to retrieve something in the parsed JSON while you also used it to retrieve the data from the initial array. All and all I think you need to reconsider you code in the first place.

Upvotes: 0

MasNotsram
MasNotsram

Reputation: 2273

That's because there is no leftNav[1]. Your array only includes one object:

"leftnav":[{"navtitle":"Nav Two","navdesc":"Two Link","navimage":"http://graph.jpg"}]

Change this:

alert(finalobj.leftnav[x].navtitle);

to this:

alert(finalobj.leftnav[0].navtitle);

Upvotes: 1

Related Questions