[Fixed] Angular Typescript Push Object into Array, Making Sense of Errors

Issue

So I am trying to create an array of objects with windows.localstorage in my app.

export class MyListComponent implements OnInit {

  public myStorage = window.localStorage;
  public list : any [] = [];
  public empty = true;

  constructor() { }

  ngOnInit(): void {

    for(var k in window.localStorage) {
      var temp = this.myStorage[k].split(",");
      console.log(temp);
      if(temp.length == 4) {
        let item = {
          id: k,
          type: temp[1]
        }
        this.empty = false;
        this.list.push(item);
        console.log(item);
      }
    }
    console.log(this.list);
  }

}

For some reason, the last line console.log(this.list) does not seem to be working, or in otherwords, nothing is added to it. I am not sure why this is, as all the other console logs seem to working, such as console.log(temp) and console.log(item). My console also shows the following error:

ERROR TypeError: this.myStorage[k].split is not a function at MyListComponent.ngOnInit

Why is that? If it didn’t successfully split, then temp wouldn’t have been created. How can I add my item objects into my list array, and why is there a typeerror for this.myStorage.split?

Solution

You could try like below. Also it’s not advisable to use for…in loops for these kind of instances like localStorage as it iterates over all enumerable properties not just own properties.

Object.keys(window.localStorage).forEach(k => {
    const value = window.localStorage[k];
    if (value) {
        var temp = value.split(",");
        console.log(temp);
        if (temp.length == 4) {
            let item = {
                id: k,
                type: temp[1]
            }
            this.empty = false;
            this.list.push(item);
            console.log(item);
        }
    }
});

Leave a Reply

(*) Required, Your email will not be published