Home > front end >  localStorage Array Objects - How to check is Object Key Value exists
localStorage Array Objects - How to check is Object Key Value exists

Time:11-09

How would i check to see if the ID exists within the localStorage object key array

i am currenty using this and it does not work

if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }

Also how do i pull the indivdual object array apart into ID , image , title to make varibles

Thank you

Below is the Full Code

function checkfave (theid) {

// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage' theid).attr('src');
var thetitle = $('#thetitle' theid).text();

if (localStorage.getItem('favorites') != null) {
    if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }
}
            
    favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
    localStorage.setItem('favorites', JSON.stringify(favorites));

    alert('You Just Added Listing ' theid ' To Your Favorites');


    //Loop through the Favorites List and display in console (HIDDEN)
    console.clear();

        for (let i = 0; i < favorites.length; i  ) { 
            console.log('ID= ' favorites[i].ID '  IMAGE=' favorites[i].IMAGE '  TITLE=' favorites[i].TITLE);
        }//for loop
                                                
}

CodePudding user response:

When you parse json using JSON.parse, a javascript object is created. You can access keys in javascript objects by simply using the bracket notation:

object[key] = value

If a key is not defined in an object, when you request the key you will get undefined. undefined is equivalent to false when evaluating an if clause so you can simply use

if (favorites[theid]) { alert('You Allready Added this Listing'); }

CodePudding user response:

I found a solution after the suggestions

My solution was to check within a for loop using favorites[i].ID == theid

The final code is below. i am very sure it could be done another way, But this works for now.

function checkfave (theid) {

var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage' theid).attr('src');
var thetitle = $('#thetitle' theid).text();
var added=true;

    //Loop through the Favorites List and display in console (HIDDEN)  
    for (let i = 0; i < favorites.length; i  ) { 
            
    if ( favorites[i].ID == theid ) { alert('You allready Added Listing ' theid ' To Your Favorites'); var added=false; break; } else {var added=true;}
    
    }//for loop
        
                
        if (added===true) {
            favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
            localStorage.setItem('favorites', JSON.stringify(favorites));
            alert('You Just Added Listing ' theid ' To Your Favorites');
        }


                                                
}
  • Related