Push an object into array using for loop and saving it into lcoalstorage


const addaccount = () => {
    let accountlist = [];
    let accountform = {
     "accountno" : document.getElementById("account").value,
     "custname" : document.getElementById("name").value,
     "balance" : document.getElementById("balance").value
    }
    for(let i = 0; i < accountlist.length; i++){  
        accountlist.push(accountform);
    }
    localStorage.setItem("Accountlist",  JSON.stringify(accountlist));
    
}

Expected output: Save account form details that I input but it’s saving empty array instead. Any help would be appreciated.

Not really sure about the symbol you’ve used, but I assume it’s an empty array

let accountlist = [];

This means that your loop will never run.

Also please take a look on how to format code so it will be easier for people to read and help

As well as welcome to the forum :sparkles:

Thanks for replying and yeah I’ll take care of the format of asking question next time. Also if i don’t use let accountlist = [ ], how can I save the “accountform” entries as many times I click button in local storage? I removed “let accountlist = [ ]” but it’s only saving one account form entry in local storage

I guess it depends on your needs, requirements and needs; there are multiple ways of doing it.

1 - since you’ve talked about clicking button I guess the starting point is listening to the event.

2 - Now it depends on your page/data/content but the general idea is to collect all the data you need first then add it into localStorage on the event handler.

Hope this clarify your ideas.
Feel free to post more details if you need further help :slight_smile:

Let me explain my whole problem. I have a form “create account” with account number field, name field, balance field and I also have a button. Now I added a function create account code is below.

const addaccount = () => {
let accountlist = [];
let accountform = {
“accountno” : document.getElementById(“account”).value,
“custname” : document.getElementById(“name”).value,
“balance” : document.getElementById(“balance”).value
}
for(let i = 0; i < accountlist.length; i++){
accountlist.push(accountform);
}
localStorage.setItem(“Accountlist”, JSON.stringify(accountlist));

}

Now with your suggestion, I removed accountlist[ ] because for loop will not execute with empty array and then I added

const addaccount = () => {
    let accountform = {
     "accountno" : document.getElementById("account").value,
     "custname" : document.getElementById("name").value,
     "balance" : document.getElementById("balance").value
    }
    for(let i = 0; i < accountform.length; i++){  
        accountform[i];
    }
    localStorage.setItem("Accountlist", JSON.stringify(accountform));
}
document.getElementById('crtacc').addEventListener('click', addaccount);

Now it’s only saving one accountform entry in local storage but I want it to save as much accountform entries as I enter. For e.g if I add one entry “account input value”, “name input value”, “balance input value” it will save one entry and if i add another it will save that too without overwriting previous one. Hope now you can understand my problem.

This isn’t doing anything at all. You’re looping, but that’s it.

You are trying to save an account entry, you don’t need to loop.

const addaccount = () => {
   localStorage.setItem("accountno", document.getElementById("account").value);
   localStorage.setItem("custname", document.getElementById("name").value);
   localStorage.setItem("balance", document.getElementById("balance").value);
};

Okay, I have fixed the problem by making an empty array outside function and then pushing accountform into it.

let accountlist = [];
const addaccount = () => {
    let accountform = {
     "accountno" : document.getElementById("account").value,
     "custname" : document.getElementById("name").value,
     "balance" : document.getElementById("balance").value
    }
    accountlist.push(accountform);
    localStorage.setItem("Accountlist", JSON.stringify(accountlist));
}

Can someone explain why by putting empty array inside function, I can only add one account entry, if I add more it will overwrite the previous one but when I put empty array outside function, I’m able to add multiple account entries without overwriting previous entries.

To answer your question: you are overwriting the values because you are assigning a new value to the storage.

In practice:

localStorage.setItem("test", "awesome value")

produce the following result in my LS (local storage):

{test: "awesome value"}

If later on I run

localStorage.setItem("test",  JSON.stringify([1,2,3,4,5,6]))

//{test: "[1,2,3,4,5,6]"}

So I have totally changed the value associated to the key “test”.


This means that in your code, you should update the value associated with the key first, then push it to the storage.

Hope this helps :sparkles:

It shouldn’t be an empty array here. It should be

Json.parse(localStorage.getItem("Accountlist"))

Ideally don’t do this, store each account under an ID that you search for, seperately, because atm you’re making yourself something that is very error prone (see the difficulty you’re having saving these to an array). Local Storage is extremely basic in terms of what you can store and how you store it, and you need to make it as simple as possible, rather than needing multiple serialise/deserialise steps

Thankyou everyone for your help. @DanCouper yes, you’re right, localstorage is very simple in terms of what you can store but I was complicating it by storing and then retrieving and then changing value of it’s one stored object property. It was becoming really messy. Can you suggest another approach for my project. I’m dropping link here also I have another question jQuery in my project is working in codepen but not in browser.