Created
April 5, 2018 13:10
-
-
Save spelcaster/3029f8c134533ea83fde53c237896bbb to your computer and use it in GitHub Desktop.
Construct new array of objects from object array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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