Juggernaut
Juggernaut

Reputation: 806

How do I make it into Array of Objects in Angular 2?

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!

Upvotes: 1

Views: 67

Answers (2)

kimamula
kimamula

Reputation: 12601

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.

Upvotes: 0

Meir
Meir

Reputation: 14365

You keep nesting your values on each call to:

abc = [get];

Replace it with:

abc = get;

and it should work

Upvotes: 1

Related Questions