如果尚未在 localStorage 中,如何将新对象推送到数组

我正在尝试实现一个简单的“添加到收藏夹”功能,但不能完全让事情在本地存储中工作。


我可以将对象/数组推送到本地存储并取回它,但是当我单击下一个项目以“添加到收藏夹”时,我最终会覆盖前一个而不是向数组添加新对象。


下面的代码:


 const push1 = async (movieId, movieName, image) => {

    const stringId = JSON.stringify(movieId);

    const stringName = JSON.stringify(movieName);

    const stringImage = JSON.stringify(image);


    // our array

    let moviesList = [];


    // our object

    let movies = {

      movieId: stringId,

      movieName: stringName,

      image: stringImage

    };


    moviesList.push(movies);


    // storing our array as a string

    localStorage.setItem("movieList", JSON.stringify(moviesList));


    let updatedMoviesList = [];


    const retrievedMovies = localStorage.getItem("movieList");

    const parseRetrievedMovies = JSON.parse(retrievedMovies);

    console.log("retrievedMovies: ", retrievedMovies);

    console.log("parseRetrievedMovies: ", parseRetrievedMovies);

    parseRetrievedMovies.push(movies);

};

如果同一个对象不存在,我该如何更新数组?


桃花长相依
浏览 144回答 3
3回答

手掌心

也许您可以Set()改用它来帮助您将独特的电影存储在localStorage.尝试如下:const stringId = '12';const stringName = 'Name';const stringImage = '<img-url>';const moviesList = new Set();const movie = {&nbsp; movieId: stringId,&nbsp; movieName: stringName,&nbsp; image: stringImage};moviesList.add(JSON.stringify(movie));console.log('first attempt', JSON.parse(Array.from(moviesList)));moviesList.add(JSON.stringify(movie));console.log('second attempt', JSON.parse(Array.from(moviesList)));

慕森王

您的功能没有读取旧设置。相反,您从一个新的空数组开始:let&nbsp;moviesList&nbsp;=&nbsp;[];在这里,您可以改为加载上次保存的数据,如下所示:let&nbsp;moviesList&nbsp;=&nbsp;localStorage.getItem("movieList");然后通过添加新电影来修改它,然后保存,就像你已经在做的那样。希望这可以帮助。

慕桂英3389331

检查对象是否已经在检索电影中array.some,并且只有在不存在时才推送它。const retrievedMovies = localStorage.getItem("movieList");if(retrievedMovies) {&nbsp; &nbsp;const parseRetrievedMovies = JSON.parse(retrievedMovies);&nbsp; &nbsp;console.log("retrievedMovies: ", retrievedMovies);&nbsp; &nbsp;console.log("parseRetrievedMovies: ", parseRetrievedMovies);&nbsp; &nbsp;const movieExists = parseRetrievedMovies.some((m) => movies.movieId === m.movieId ))&nbsp; &nbsp;if(!movieExists) {&nbsp; &nbsp; &nbsp; parseRetrievedMovies.push(movies);&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript