-1

I am trying to retrieve value from localStorage but below code is printing NULL in browser Console instead of array object values! any one can help me with this please

var ary = [];

function setFavorite(n, v) {
    alert("a=" + n + " ,v=" + v);
    var obj = {};
    obj[n] = v;
    ary.push(obj);
    // Put the object into storage
    localStorage.setItem('testObject', JSON.stringify(ary));
    // Retrieve the object from storage
    var retrievedObject = localStorage.getItem('ary');
    console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
setFavorite("Power", "Power Converter"); //calling above function from a button click

2 Answers 2

2

You are adding the object under the testObject key but you are fetching the value of the ary key, hence why nothing is returned.

JSFiddle with a simple illustration for adding and retrieving arrays from localStorage

Sign up to request clarification or add additional context in comments.

3 Comments

can you tell me , how can i retireve it back in for each loop so that i can print Name & value in console together
Do you mean that you want to retrieve the array stored in localStorage and then look over everything printing key and value?
How can i push only unique names which are not available in ary
1

Hm, typo I guess: 'ary' hasn't been stored.

You stored "testObject".

var retrievedObject = localStorage.getItem('testObject'); 

should do the trick.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.