Reputation: 3920
i have a json data .
data ={{"id":"10","name":"test"},{"id":"10","name":"test1"},{"id":"11","name":"tsst"},{"id":"41","name":"jhkj"},{"id":"11","name":"yuyyu"},}
from the json data i am fetching the id to get location
from a database table as follows
data.each(function( index ) {
var id = index.id //gets 10
//again gets 10 and again doing db operations for same id value
//db operations
//get location details from db using this id
// operations after getting locations....................
});
my proble is id
is repeated ie 10,10,11,41 ,11
.so calling db
operations for repeated values also.How can i avoid by calling db operations for repeated id values .
Upvotes: 0
Views: 5146
Reputation: 22323
Check for duplicate ID may solve your problem.
For Example:
var dup= {};
data.each(function( index ) {
var id = index.id;
dup.push(id);
if (dup[id])
$(this).remove(); //OR DO nothing
else
//Your DB Operation
});
Upvotes: 2
Reputation: 388316
Try
var temp = {};
for(var i = 0; i < data.length ; i++ ){
var obj = data[i];
if(temp[obj.id] >= 0){
data.splice(i, 1);
i--;
}
temp[obj.id] = i;
}
console.log(data)
Demo: Fiddle
Upvotes: 3
Reputation: 2500
Create another array and add the value in it after checking that it exists or not.
you can use inArray ref : http://api.jquery.com/jQuery.inArray/ for this purpose.
Upvotes: 0
Reputation: 11579
I think you have to avoid to call DB operations for all id in the loop. Just pass everything to backend and get data for all id which you need within one DB operation.
Upvotes: 0