ServerSideSkittles
ServerSideSkittles

Reputation: 2973

Loop JSON and stop when condition met. Then count the objects

I have a json file with a list of users and points. I want to somehow Loop through until the _id == userId, then count how many objects there are to get their position.

So far I have this json file which has the points in desc order already

[  
  {  
    "_id":"55db8684ce3bf55b4b612a72",
    "firstname":"Billy",
    "lastname":"Bob",
    "points":3109373
  },
  {  
    "_id":"55dbdffeaba8ee274d3b9f89",
    "firstname":"Steve",
    "lastname":"Jones",
    "points":34434
  },
  {  
    "_id":"55dbdbf756b0fa064dd3e507",
    "firstname":"Jim",
    "lastname":"Kirk",
    "points":1000
  },
  {  
    "_id":"55dbdc2756b0fa064dd3e508",
    "firstname":"Casey",
    "lastname":"Jones",
    "points":36
  },
  {  
    "_id":"55dbdbd656b0fa064dd3e506",
    "firstname":"Reg",
    "lastname":"Barclay",
    "points":33
  },

]

What I need to do is find the position for the user using their ID. So far I have but the position always returns undefined.

$.each(obj, function(index, value) {    

       var returnObj = (this === "<%= user._id %>"); 
       var position = returnObj.length;
       console.log('user position is ' + position);

});

But this always returns undefined 11 times, which is what the position should be.

Upvotes: 0

Views: 893

Answers (1)

bipen
bipen

Reputation: 36531

If I got you right, using for instead of each works which is much faster and not much to code.

try this,

for(var i =0;i < obj.length; i++)
{
  if(obj[i]['_id'] == "55dbdc2756b0fa064dd3e508"){
     alert('position :' +  parseInt(i + 1));  //<--position in an obj
     alert('index :' + i); //<----actual index
     break;
  }
}

var obj=[  
  {  
    "_id":"55db8684ce3bf55b4b612a72",
    "firstname":"Billy",
    "lastname":"Bob",
    "points":3109373
  },
  {  
    "_id":"55dbdffeaba8ee274d3b9f89",
    "firstname":"Steve",
    "lastname":"Jones",
    "points":34434
  },
  {  
    "_id":"55dbdbf756b0fa064dd3e507",
    "firstname":"Jim",
    "lastname":"Kirk",
    "points":1000
  },
  {  
    "_id":"55dbdc2756b0fa064dd3e508",
    "firstname":"Casey",
    "lastname":"Jones",
    "points":36
  },
  {  
    "_id":"55dbdbd656b0fa064dd3e506",
    "firstname":"Reg",
    "lastname":"Barclay",
    "points":33
  },

]


for(var i =0;i < obj.length; i++)
{
    if(obj[i]['_id'] == "55dbdc2756b0fa064dd3e508"){
       alert('position :' +  parseInt(i + 1));
       alert('index :' + i);
       break;
    }
}

Upvotes: 3

Related Questions