Reputation: 13
I write a function initMap(response){....}
.The response is an array of objects look like
In console :
(6)[{…}, {…}, {…}, {…}, {…}, {…}]
0: {latitude: "17.0009", longitude: "82.2108"}
1: {latitude: "17.0504", longitude: "82.1659"}
2: {latitude: "17.1529", longitude: "82.2228"}
3: {latitude: "17.1621", longitude: "82.1921"}
4: {latitude: "17.0004", longitude: "82.2211"}
5: {latitude: "17.1235", longitude: "82.1926"}
length: 6
__proto__: Array(0)
I want the output of an array like
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {lat: 17.0009, lng: 82.2108}
1: {lat: 17.0504, lng: 82.1659}
2: {lat: 17.1529, lng: 82.2228}
3: {lat: 17.1621, lng: 82.1921}
4: {lat: 17.0004, lng: 82.2211}
5: {lat: 17.1235, lng: 82.1926}
length: 6
__proto__: Array(0)
For getting this I tried in the way using replace
var eventlist = JSON.stringify(response);//Jsonresult
console.log(eventlist);
var eventstring = new String();
eventstring = eventlist.replace(/"/g, "");
events = eventstring.replace(/latitude/g, "lat").replace(/longitude/g, "lng");
console.log(events);
While doing this I am getting the result in console as this way
[{lat:17.0009,lng:82.2108},{lat:17.0504,lng:82.1659},{lat:17.1529,lng:82.2228},{lat:17.1621,lng:82.1921},{lat:17.0004,lng:82.2211},{lat:17.1235,lng:82.1926}]
it look like as string but i need the output as
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {lat: 17.0009, lng: 82.2108}
1: {lat: 17.0504, lng: 82.1659}
2: {lat: 17.1529, lng: 82.2228}
3: {lat: 17.1621, lng: 82.1921}
4: {lat: 17.0004, lng: 82.2211}
5: {lat: 17.1235, lng: 82.1926}
length: 6
__proto__: Array(0)
How to do this please give me an idea about this.
Upvotes: 1
Views: 99
Reputation: 633
Well there is not other better option than map. Another alternative with syntactical sugar-
var arr =[{latitude: "17.0009", longitude: "82.2108"},{latitude: "22.0009", longitude: "33.2108"}];
let result = arr.map(({ latitude, longitude })=>{
return {
lat: +latitude,
lng: +longitude
}
});
console.log(result);
Upvotes: 0
Reputation: 37775
You can use map and destructuring assignment
let arr = [{latitude: "17.0009", longitude: "82.2108"},{latitude: "17.0504", longitude: "82.1659"},{latitude: "17.1529", longitude: "82.2228"},{latitude: "17.1621", longitude: "82.1921"},{latitude: "17.0004", longitude: "82.2211"},{latitude: "17.1235", longitude: "82.1926"}]
let op = arr.map(({latitude:lat, longitude:lng}) => ({lat:+lat, lng:+lng}))
console.log(op)
Upvotes: 1
Reputation: 371138
Use .map
to iterate over the array and create a new object for every item:
const output = arr.map(({ latitude, longitude }) => ({
lat: Number(latitude),
lng: Number(longitude)
});
Upvotes: 3
Reputation: 22500
use Array#map
function to recreate the object you want .Use parseFloat
to covert sring to number
var arr =[{latitude: "17.0009", longitude: "82.2108"},{latitude: "22.0009", longitude: "33.2108"}];
var res = arr.map(a=> ({lat:parseFloat(a.latitude),lng:parseFloat(a.longitude)}))
console.log(res)
Upvotes: 0