Skip to content Skip to sidebar Skip to footer

Json How Find Another Value At The Same Index From A Value In Javascript Object

A simple question I'm sure, but I can't figure it out. I have some JSON returned from the server while ($Row = mysql_fetch_array($params)) { $jsondata[]= array('adc

Solution 1:

For one you can simply use the ID attribute of the DIV to store a unique string, in your case it could be the index.

We do similar things in Google Closure / Javascript and if you wire up the event in the loop that you are creating the DIV in you can pass in a reference to the "current" object.

The later is the better / cleaner solution.

Solution 2:

$(".wShip").click(function(){
  var id = $(this).id;
  var result;

  WShipsObject.Ships.each(function(data) {
    if(data.adSNU == id) {
      result = data;
    }  
  });

  console.log(result);
}

Solution 3:

I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.

In the solution I created a custom attribute called key into which I stored the index.

newWShip.key = i;

Later when I need the index back again I can use this.key inside the JQuery .click()method:

var key = this.key;
var adt = WShipsObject.Ships[key].adt;

You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.

Post a Comment for "Json How Find Another Value At The Same Index From A Value In Javascript Object"