Skip to content

Instantly share code, notes, and snippets.

@spelcaster
Created April 5, 2018 13:10
Show Gist options
  • Save spelcaster/3029f8c134533ea83fde53c237896bbb to your computer and use it in GitHub Desktop.
Save spelcaster/3029f8c134533ea83fde53c237896bbb to your computer and use it in GitHub Desktop.
Construct new array of objects from object array
let response = [
{
title: "Map marker 1",
lat: 10.0,
lng: 10.0
},
{
title: "Map marker 2",
lat: 11.0,
lng: 11.0
},
{
title: 'Akward object'
}
]
function markerToPosition(marker) {
// you can do some asserts here
// assert(typeof marker.title === 'string')
// or handle errors
if (!marker.hasOwnProperty('lat') && !marker.hasOwnProperty('lng')) {
throw 'Invalid object'
}
return {
position: {
lat: marker.lat,
lng: marker.lng
}
}
}
response.forEach(function (marker, i) {
// you'll modify response instead of create another Array
try {
response[i] = markerToPosition(marker)
} catch (e) {
delete response[i]
}
})
console.log(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment