2
var bookobj = {
    Name: name,
    Author: author,
    Edition: edi,
    Price: pri
}

var arr = [];
if(localStorage === null){
    localStorage.setItem("Arrayobj", JSON.stringify(bookobj));
} else {
    arr.push(bookobj);
    localStorage.setItem("Array", JSON.stringify(arr));   
}

I have made an object and pushing it to array. but the details overwrites itself every time in localStorage.

Dadhich Sourav
  • 289
  • 6
  • 19
  • 2
    `if(localStorage === null)`? `localStorage` is never null. You need to check if `localStorage.getItem("Arrayobj")` is null (or maybe `getItem("Array")`, you need to decide what to call it) – JJJ Mar 07 '18 at 06:17
  • @JJJ, its working but the i cant insert data multiple time. – Dadhich Sourav Mar 07 '18 at 06:20
  • Yes, like @jjj mentioned, localstorage is never null. Only case when localstorage is null is when it is not supported by the browser. – gurvinder372 Mar 07 '18 at 06:20
  • Thats not the issue, The thing is how can i insert different bookobj items multiple times – Dadhich Sourav Mar 07 '18 at 06:22
  • Maybe it's because you are pushing data to **`arr1`** and then saving the contents of **`arr`**. – JJJ Mar 07 '18 at 06:24
  • @jjj ignore that arr1 and arr.. thats a typo mistake... otherwise is it correct?? – Dadhich Sourav Mar 07 '18 at 06:28
  • @DadhichSourav The code doesn't work as you're expecting. Most likely you've saved the first value at some point before adding the condition. Currently your code simply doesn't save any `Arrayobj`. – Teemu Mar 07 '18 at 06:28
  • *Show your actual code* or at least make an example that replicates the problem ([mcve]). This one has just too many issues to tell what is a "real" problem and what's just a typo. – JJJ Mar 07 '18 at 06:31

1 Answers1

4

Try this, with added comments for an explanation of how it works.

var bookobj = {
  Name: name,
  Author: author,
  Edition: edi,
  Price: pri,
}

// read what the 'books' value currently is
// the `|| '[]'` makes it so that, if it's null, it defaults to a string of an empty array
// which, when passed to JSON.parse, turns into an empty array
var books = JSON.parse(localStorage.getItem('books') || '[]')

// add the book object to the temporary books variable
books.push(bookobj)

// re-save it back to local storage
localStorage.setItem('books', JSON.stringify(books))

Your current code doesn't work because:

  1. The if (localStorage === null) line doesn't actually check for the variable in local storage. To do that, you'd do if (localStorage.getItem('...') === null). However, I've opted to use || in my solution for cleanliness.

  2. Creating the array every time and saving it will continually overwrite the array that's in storage, instead of reading and adding to what's already in storage.

  3. In the first part of the if statement, the array isn't actually saved to storage, only the bookobj itself.

kingdaro
  • 11,528
  • 3
  • 34
  • 38