Bas Bas - 1 month ago 6
TypeScript Question

Typescript append existing data from http get overwriting an existing object

This is a question of an extension of a previously asked question.
I have data in the ngOnInit see below and these fields are nor the same as the markers object.

Data from http get in my data.service.ts appending to

items:any = [];

ngOnInit() {
this.dataService.fetchData(this.slug)
.subscribe(
(data) => {
this.checkData(data);//in this function its going to be appending to this.items
}
);
}


checkData(data) {
if (data.length === 0) {
return this.router.navigate(['']);
}
return this.items = data;
}

markers =[
{
lat: 51.673858,
lng: 7.815982
},
{
lat: 51.373858,
lng: 7.215982
},
{
lat: 51.723858,
lng: 7.895982
}


]

So how can i overwrite the existing markers object with my this.items object (in this object is lat and lng available).

removing qoutes

Awnser was correct from @Eric N and made the marker.latitude and marker.longitude parseFloat().

Answer

Oh is your app mapping to markers.lat and markers.lng but you are receiving data.latitude and data.longitude? It'd be a lot cleaner to change your markers and app to use the same keys as your data source. But if your stuck using two types of data objects, you can map your received data to a new object with the right keys.

let newItems:any[] = [];

for (var element in data) {  // map over the data type
  let marker = data[element];
  newItems.push(
    { 
        lat: marker.latitude, // create new objects matching the keys used in the app
        lng: marker.longitude
    }
}

this.items = newItems;  // and assign
Comments