0

myObj is storing the input coming from the user which is pushed to arr which is store in localStorage as a 'data' key. On submit, I want the new values to be added to arr and not overwrite it (in the else part). The following code works but overwrites the old data:

var myObj = {
    field1: fname.value,
    field2: lname.value,
    field3: birth.value,
    field4: salary.value,
    field5: String(selectedGender),
    field6: String(choicesOfHobby),
    field7: color.value,
    field8: String(choicesCountry),
    field9: textArea.value
}  
    const arr = new Array()
if (window.localStorage.length == 0) {
   const arr = JSON.stringify(myObj); 
   window.localStorage.setItem('data', arr);
} else {
    const arr = JSON.stringify(myObj); 
   window.localStorage.setItem('data', arr);
}
Mustafa Anas
  • 31
  • 1
  • 9
  • 1
    `arr` isn't an array, and nothing gets pushed here. If you want an array of objects, you need to actually use an array of objects. –  Jan 15 '19 at 14:02
  • 1
    localStorage is actually a key, value storage so you cannot have two same keys... and doing JSON.stringify won't convert an Object to array... – Muhammad Jahanzeb Jan 15 '19 at 14:02
  • `setData('data')` means you set the data to x, so you overwrite data yourself. In other words, your if/else clause does nothing, since both if and else set the same item to the same key in localStorage. Use two different names? – Shilly Jan 15 '19 at 14:06
  • I know and I still want the same key, but I want to update its value so its the old one + a string of the new myObj which is the input – Mustafa Anas Jan 15 '19 at 14:07
  • I am instructed to use the same key – Mustafa Anas Jan 15 '19 at 14:07
  • then you need to get the Item from storage first... then do the JSON.parse and add the new key and then stringify it and save it back to localStorage – Muhammad Jahanzeb Jan 15 '19 at 14:08

5 Answers5

0

Your mistakes:

  1. arr, despite its name, isn't an array.
  2. you never recover the saved data

Check the code below to see my take on the problem: (before trying it, you should erase your localStorage)

var myObj = {
    field1: fname.value,
    field2: lname.value,
    field3: birth.value,
    field4: salary.value,
    field5: String(selectedGender),
    field6: String(choicesOfHobby),
    field7: color.value,
    field8: String(choicesCountry),
    field9: textArea.value
}
const array = window.localStorage.data || []; // get your saved array, or create a new one
array.push(myObj); // Add the current item to the array  
window.localStorage.setItem('data', JSON.stringify(array)); // save it again

Any further question please just ask

dquijada
  • 1,697
  • 3
  • 14
  • 19
0

You need to use something like this:

let data = localStorage.getItem('data');
let dataObj = JSON.parse(data);
dataObj[fieldKey] = fieldObj;
localStorage.setItem('data', JSON.stringify(dataObj));
0

Firstly read localstorage documents how to use it: https://developer.mozilla.org/tr/docs/Web/API/Window/localStorage You have to push data array to localstorage and push your objects to your data array after getting data array from localstorage. Finally don't forget to set your data array to localstorage again. Your localstorage part code should be like below:

    var data = JSON.parse(window.localStorage.getItem("data"));
    if(data === null){
     data = [];
    }
    data.push(myObj);
    window.localStorage.setItem("data",JSON.stringfy(data));
mstfyldz
  • 482
  • 1
  • 6
  • 12
0

One thing to note is that JSON.stringify returns a string, not an array -- and, conveniently, localStorage stores key/value pairs where the value is a string, so this all works as it's supposed to.

To update the value in localStorage, you could first retrieve it, then modify it however you like, and then store it again. Since you're working with javascript objects, you'll need to use JSON.parse and JSON.stringify to convert back and forth between objects (to work with) and strings (to store). This pattern looks like:

let retrievedString = localStorage.getItem('data');
let retrievedObject = JSON.parse(retrievedString); // convert string to obj
let oldColor = retrievedObject.field7; // we don't actually use oldColor
let newColor = "#666666"; 
retrievedObject.field7 = newColor; //change existing property
retrievedObject.field99 = "99"; // add new property
let modifiedString = JSON.stringify(retrievedObject); // ready to store new version
localStorage.setItem('data', modifiedString);

I added more to the code sample to clarify the kinds of things you can do with your retrieved object before converting back to a string and finally replacing the old version in storage.

Cat
  • 4,141
  • 2
  • 10
  • 18
  • Exactly! But now how do I replace the "... this will ... " with my object so that it is properly stored in the localStorage so that I can access it later? – Mustafa Anas Jan 15 '19 at 14:15
  • Please see my edited answer. Is this clear? -- I'll add another code sample to clarify. – Cat Jan 15 '19 at 14:18
  • I did this let arr = new Array() arr = JSON.parse(window.localStorage.getItem("data")); arr.push(myObj); const arrPush = JSON.stringfy(arr) window.localStorage.setItem("data",arrPush); But it says arr.push is not a function – Mustafa Anas Jan 15 '19 at 23:22
  • The reason is that `push()` only works on arrays, and `arr` isn't an array. (Javascript is dynamically typed, so even though you declared it as an array, it gets automatically converted into a javascript object when you assign the result of `JSON.parse()` to it.) To add something to an object, you use `let myNewValue = "whatever"; arr.myNewKey = myNewValue;` (See https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics if this isn't clear.) – Cat Jan 16 '19 at 23:06
-1

You just need to use this:

arrInStorage = localStorage.getItem('data') || [];
arr = JSON.parse(arrInStorage);
arr.push(myObj);
localStorage.setItem('data', JSON.stringify(arr));

instead of your if / else statement.

markmoxx
  • 1,492
  • 1
  • 11
  • 21