Say I am being provided a json object that looks like this:
{"someList": [{"id": "21154859" },{"id": "21154865" },{"id": "21154856" },{"id": "21154870" }]}
I want to find out what the index number of the current ‘someList’ item I am on.
I have the someList item id and it is represented by the var aid and equals : 21154856.
I have created a function like so:
$.getJSON( url, function( data ) {
var jsonLength = data.someList.length;
for ( i=1; i <= jsonLength; i++ ){
chx = data.someList[i].id;
if(chx === aid){
var currentidno = Number(i) + 1;
$('#page').html('').append(currentidno + ' of ' + jsonLength);
break;
}
}
});
When I set this up it works fine and gives me a result like this:
3 of 4
But it feels inefficient and I wonder how it would perform if there were thousands of possibilities. Can someone weigh in on whether or not this ia the best way to achieve what I want to do and either verify or deny the assumption that this is a good way to accomplish the task?
No. The loop is just the way to go. However, if you need to do that search often on many elements, it might be efficient to build an index (or just deliver the JSON as an Array of numbers at once, if there are no other properties):
Or you could with indexing by object properties, instead of an array: