Person
Person

Reputation: 2259

Populate object with data from localStorage

I have options in select with individual ids which I want to store in localStorage as an object when I click on link.

On link click I run function:

let obj = {};
    if(options.length) {

              for(let i = 0; i < options.length; i++) {
                let item = options[i];

                    obj[item._id] = null;
                }

                  localStorage.setItem('key', JSON.stringify(obj));
    }

After I click link popup opens where I click the button and it adds value to one of the property of object.

This function looks like this.

  let data = JSON.parse(localStorage.getItem('key'));
              for(let p in data) {
                if($location.search().item === p) {
                  data[p] = response.data;
                  localStorage.setItem('key', JSON.stringify(data));
                }
              }  

I want to be able to do that for every select and store to each id corresponding response.data; Problem right now is that when I click link for the second time all of my stored values turn to null, because of this line I think

obj[item._id] = null;

How can I keep value which already was set untouched?

Structure of object something like this:

let obj = {
1: 'response1',
2: 'response3'
}

Upvotes: 2

Views: 259

Answers (1)

Juho
Juho

Reputation: 427

Assuming you're dealing with overwriting stuff within the reinitialisation, Steffi's on the right track, but array_key_exists doesn't exist in javascript. Also you'd need to read the current values from localStorage to know which fields are already set.

let obj = JSON.parse(localStorage.getItem('key')) || {};
// [...]
obj[item._id] = obj[item._id] || null;

should do the job: don't overwrite items that already exist. Better yet, why reinitialise at all, assuming options don't change over time:

if(options.length && !localStorage.getItem('key'))

Besides that is there a reason for iterating over all the keys of data and calling search multiple times? Might cause some problems, might not. Something like this might work for your case:

let data = JSON.parse(localStorage.getItem('key'));
const item = $location.search().item
if(data[item]) data[item] = response.data;
localStorage.setItem('key', JSON.stringify(data));

Upvotes: 1

Related Questions