Reputation: 401
I have this code here http://jsfiddle.net/so0rL8kj/3/
and I'm having trouble implementing a check of does input already exist in object array.
I've tried looping over json.parse(urls) something like this
if (this.url == id) {
console.log("found: " + JSON.stringify(this));
$(".order").append("<li>" + id + " ... already exists in your list.</li>");
return false;
}
But that did not stop the code from executing the localstorage.setitem save. I also tried to save as an array and then using inArray() but had no results with this functionality either.
How do I add a check to stop duplicates from user input for localstorage?
edit: working fiddle http://jsfiddle.net/so0rL8kj/4/
Upvotes: 0
Views: 745
Reputation: 171669
You can't use $.inArray()
to compare a string to an array of objects.
Array would look something like:
[{"url":"someVal"},{"url":"Anotherval"}]
All $.inArray()
will do is look at each object, and will never find a match since you are looking for the value of an object property in each element of the array
You can use a for loop to iterate the array and compare each url
property to the string or use various array methods like Array.prototype.filter()
var alreadyExists = arrayCheck.filter(function(item){
return id ==== item.url
}).length;
This filters the array to objects that match the url to id and if it has no length there is no match
Upvotes: 1