1

I currently have a json object, that I loop through and output a list of links.

See fiddle: http://jsfiddle.net/jasonday/hzZ8j/

each link is given an id based upon the storeID in the json.

What I want to do, is when a link is clicked it finds the id in the json, and then writes the sibling element "otherData" to #otherDataDiv

I've worked with traversing xml, but I'm not sure how to accomplish this with json.

Any help would be appreciated. thanks.

Jason
  • 7,612
  • 14
  • 77
  • 127

1 Answers1

2

You just have to loop over, like this:

var target = "store17",
    foundStore = {};
for(var k1 in object.state){ var state = object.state[k1];
  for(var k2 in state.store){ var store = state[k2];
    if (store.storeid == target){
      foundStore = store;
      break;
    }
  }
}

However, if you were using jQuery templates then you could just look for 'tmplItem' in the data array on the element.

Additionally, if you weren't building the HTML manually for this, I would suggest using jQuery data here for this project. It would solve your problem immensely.

to store: $(selector).data('unique name here',data);

to retrieve: var usefulname = $(selector).data('unique name here');

and then in your onclick for each link you could:

var otherData = $(this).data('unique name here').otherData;
jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • hey jcolebrand, I'm not sure what you mean by the second part of your answer, with jquery data. Any chance you can elaborate, or update my fiddle to reflect your point? – Jason Dec 14 '11 at 20:13
  • I can update the jsfiddle, but I'm going to be redoing part of it a fair bit. it would be easier to do it with jQuery templates, ok? – jcolebrand Dec 14 '11 at 20:47
  • that would be fine. I'm more comfortable with jQuery, but haven't used templates before. – Jason Dec 14 '11 at 20:50
  • Check this one http://jsfiddle.net/hzZ8j/51/ and notice that it's broken on one part (you can't have a space in id names) and I'm going to fix that. This was just a sort of hack to show something, hang tight for more. – jcolebrand Dec 14 '11 at 21:01
  • In this one, see that I updated the OL to have a different ID (replaced spaces with underscores) http://jsfiddle.net/hzZ8j/53/ – jcolebrand Dec 14 '11 at 21:06
  • Interesting approach. I'll give it a shot and get back to you. Because I will need to be able to grab data out of the json through various functions, so this does look like a better choice overall. – Jason Dec 14 '11 at 21:14
  • Ok, so here is the final product, and you should be able to follow the logic pretty clearly. Ask where you're not sure. http://jsfiddle.net/hzZ8j/61/ – jcolebrand Dec 14 '11 at 21:31
  • Looks good, I'll look into the logic so I have a complete understanding of what's happening. Thanks for the help! – Jason Dec 14 '11 at 21:41
  • What's that? I'm kind of lost? For starters, the tmpl-engine adds a jQuery.data of every bound element. – jcolebrand Dec 14 '11 at 21:55