Reputation: 70
I'm having a problem with my $.getJSON
function, first I store all my friends in a array like this:
var friends = [];
friends.push({
user: {
username: value.username,
uuid: value.uuid,
accepted: value.accepted,
sent: value.sent
}
});
This get's it's data from a $.getJSON
function and works fine.
Then I have a search function, where I search for a username from my database like this:
$(document).on('keyup', '.search', function() {
$.getJSON('url?username='+$(this).val(), function(data){
$.each(data, function(index, value){
friends.filter(function (friend) {
if(friend.user.username == value.username){
//Append custom
} else {
//append data from JSON
}
});
});
});
});
If friends array have a object, this works fine. But if it's empty, nothing happends, it does not append anything.
What's wrong here? Any help is appreciated
Upvotes: 1
Views: 124
Reputation: 4355
You should use filter
to return the matching items in the array by evaluating whether your case is true
.
var matches = friends.filter(function (friend) {
return friend.user.username == value.username
});
if (matches.length > 0) {
//you had a match in the friends array
console.log(matches[0]);
} else {
//you didn't have a match in the friends array
}
Here is a fiddle demonstrating the idea
Upvotes: 2