1

This is my code. I am trying since a couple of days to create an Array of Objects, which I will then store in Local Storage. Here is the problem, I need to first Get the existing value from Local Storage.

I then need to add the new data object to the existing array. I then convert it into JSON so that I can store it back in the local storage.

onRegisterSubmit(){
    const user = {
        a: this.a,
        b: this.b,
        c: this.c,
      id: Date.now()
    }    

   var abc = [];
   var get =  JSON.parse(localStorage.getItem('user'));
   abc = [get];
   abc.push(user);

   localStorage.setItem('user', JSON.stringify(abc));

   console.log(JSON.stringify(abc));
   console.log(get);
  }

I want the JSON to be an array of objects like this,

[{"hour":1,"minute":21,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797882440"},{"hour":1,"minute":24,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797896257"},{"hour":6,"minute":14,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493815470408"}]

This is my JSON.

[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}]

Please help.Been trying for several days and any help will be greatly appreciated. Thankyou!

3
  • And what happens instead of it working as you wanted? Commented May 3, 2017 at 15:47
  • I don't get you @nitind Commented May 3, 2017 at 15:57
  • What error message are you getting, for starters. Commented May 3, 2017 at 16:23

2 Answers 2

1

You keep nesting your values on each call to:

abc = [get];

Replace it with:

abc = get;

and it should work

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

2 Comments

This gives an error that abc.push isn't a function.
Can you debug and tell us what type you get?
0
var abc = [];
var get = JSON.parse(localStorage.getItem('user'));
abc = [get];

should be replaced with

var abc = JSON.parse(localStorage.getItem('user')) || [];

Do not forget to execute localStorage.deleteItem('user'); to clear the wrong data which has been stored by the wrong code before you run the corrected code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.