RSA
RSA

Reputation: 1449

How to solve errors in trying to store data from an array of objects in to new one

in this code Im trying to tripID and NoteID from a web service and store them in trips then in other function by reading trips[i].noteID cache the other parameters from other web service but fallowing errors happens:

public trips= [{ "Token" : "" ,
          "UDI" : "",
          "tripID" : "",
          "NoteID":"",
          "START_ADDRESS":"",
          "END_ADDRESS":"",
          "NAME":"",
          "PHONE":"",
          "COST":"",
         }];

GetTrips(){
  let i = 0;
  let Url='http://mysitesite/gettrip/'+this.UDI+'/'+this.Token;
  console.log(Url);
  this.http.get(Url)
  .map(res => res.json())
            .subscribe(data => {            
          console.log(data);
          for(let note of data.notes) {
            this.trips[i].Token=this.Token;
            this.trips[i].UDI=this.UDI;
            this.trips[i].NoteID=note.ID;
            this.trips[i].tripID=note.TRIP;
            i++;
          }
          console.log(this.trips);
          }
    });
}

errors:

EXCEPTION: Cannot set property 'Token' of undefined

EXCEPTION: Cannot set property 'UDI' of undefined

EXCEPTION: Cannot set property'NoteID' of undefined

EXCEPTION: Cannot set property 'tripID' of undefined

Update 1: this is the latest change after @toskv post:

for(let note of data.notes) {
        let newTrip = {
            Token: this.Token,
            UDI: this.UDI,
            NoteID: note.ID,
            tripID: note.TRIP,
            START_ADDRESS :null,
            END_ADDRESS:null,
            NAME:null,
            PHONE:null,
            COST:null,
       };
          this.trips.push(newTrip);
          }
          console.log(this.trips);
          this.trips =this.trips.slice(1);
          console.log(this.trips.length);

          } 

Upvotes: 0

Views: 32

Answers (1)

toskv
toskv

Reputation: 31600

Getting the value of an index that does not exist in the array will result in the undefined value being returned.

Instead you should be pushing new values in the array.

GetTrips() {

  let Url = 'http://mysitesite/gettrip/' + this.UDI + '/' + this.Token;
  console.log(Url);
  this.http.get(Url)
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);

        for (let note of data.notes) {
          let newTrip = {
            Token: this.Token,
            UDI: this.UDI,
            NoteID: note.ID,
            tripID: note.TRIP
          };
          this.trips.push(newTrip);

        }
        console.log(this.trips);
      }
    });
}

Upvotes: 1

Related Questions