Reputation: 543
I am making a bookmark function that looks as follows:
$scope.bookmarkPost = function(bookmark_post){
if(window.localStorage.bookmarks == null) {
user_bookmarks = [];
} else {
user_bookmarks = JSON.parse(window.localStorage.bookmarks)
}
var existing_post = find(user_bookmarks, function(post){ return post.title == bookmark_post.title; });
if(!existing_post){
user_bookmarks.push({
id: bookmark_post.pagid,
title : bookmark_post.title,
date: bookmark_post.created,
room: bookmark_post.room
});
}
console.log(JSON.stringify(user_bookmarks));
window.localStorage.bookmarks = JSON.stringify(user_bookmarks);
};
This should work and indeed adds the post to a my array of objects if it allready exists, and then puts it in localstorage. As you can see I'm trying to check if there's allready an entry with the same title like this:
var existing_post = find(user_bookmarks, function(post){ return post.title == bookmark_post.title; });
To be 100% honest I'm not even 100% sure what this does, but I couldn't find anything else on my particular subject. This check doesn't work and thus there are duplicate entries. Does anyone know how it can be fixed?
Upvotes: 1
Views: 67
Reputation: 200
You probably meant to use the Array.find() method:
var existing_post = user_bookmarks.find(function(post){
return post.title === bookmark_post.title; //use === for strict comparison
}); //will return only first element that matches the callback criteria
Quick note: Array.find() is not supported by IE
Upvotes: 2