AndrewB AndrewB - 6 months ago 69
Ajax Question

loop through an array of objects does not stop on if statement

This is my first question. I have a code in which I am trying to add an object to an array in local storage. If it already exists, I check it and want to stop the loop. However, this only happens on the first element which is created when the loop is empty. Could you please, look at my code and see what I'm doing wrong. I have tried:


  • for loop

  • some

  • forEach



The arguments in the function are to fetch variables from other function, I'm using AJAX to fetch some data. I know that forEach doesn't accept return statement, that's why the code is commented out.

Thanks in advance
Code:

var counter = 0;

function bookmarkNewsSource(that, x, data, newsName) {

myBookmark = {
count: counter,
imgNum: x,
id: data.sources[x].id,
name: data.sources[x].name
};

// check if fullTask already exists
if (localStorage.getItem("bookmarks") === null) {
//if not init array
var bookmarks = [];
//add to an array
bookmarks.push(myBookmark);
counter++;
//set localstorage and convert object to a string
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
} else {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// bookmarks.forEach((bookmark, index, array) => {
// console.log(bookmark, index);
// if (newsName == bookmark.name) {
// return 'done';
// } else {
// bookmarks.push(myBookmark);
// localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
// counter++;
// }
// });

bookmarks.some((bookmark) => {
if (newsName == bookmark.name) {
console.log('yes', newsName);
return false;
} else {
JSON.parse(localStorage.getItem("bookmarks"));
bookmarks.push(myBookmark);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
counter++;
}
});
}
}

Answer Source

You had it almost right, just need to return true when you have found a match and want the loop to stop. It's better explained at MDN Array.prototype.some() -

some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value. If such an element is found, some() immediately returns true

    var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
    var isPresent = bookmarks.some((bookmark) => {
        if (newsName == bookmark.name) {
            console.log('Match Found', newsName);
            return true; //Exit loop and stop going through further elements.
        }
    });

    if (!isPresent) {
             bookmarks.push(myBookmark);
             localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
             counter++;      
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download