0

I need to create a object like this

var flightPlanCoordinates = [
   {lat: 37.772, lng: -122.214},
   {lat: 21.291, lng: -157.821},
   {lat: -18.142, lng: 178.431},
   {lat: -27.467, lng: 153.027}
];

My try is

    for (i = 0; i < sales_person_route.length; i++) {
        var flightPlanCoordinates = [
        {lat: sales_person_route[i].latitude, lng: sales_person_route[i].longitude},
];

}

But it's a wrong syntax. But I need to Object like flightPlanCoordinates. My lat, lng value available in sales_person_route. How to achieve this?

2

4 Answers 4

1

You should define an array before your for statement:

var flightPlanCoordinates = [];

and then for each item in your loop push the corresponding object.

 for (i = 0; i < sales_person_route.length; i++) { 
    var salesPersonRoute = sales_person_route[i];
    flightPlanCoordinates.push({ lat: salesPersonRoute.latitude
                               , lng: salesPersonRoute.longitude
    });
}

Or you could try this:

var flightPlanCoordinates = sales_person_route.map(item => {
    return {
        lat: item.latitude, 
        lng: item.longitude
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1
var finalArray = [];
for (i = 0; i < sales_person_route.length; i++) {
    let flightPlanCoordinates = {
        lat: sales_person_route[i].latitude,
        lng: sales_person_route[i].longitude
    };
    finalArray.push(flightPlanCoordinates);
}

Comments

1

The Array object has a great function available, map, made just for this purpose:

var sales_person_route = [
   {latitude: 37.772, longitude: -122.214},
   {latitude: 21.291, longitude: -157.821},
   {latitude: -18.142, longitude: 178.431},
   {latitude: -27.467, longitude: 153.027}
];
var flightPlanCoordinates = sales_person_route.map(r => { 
  return { 
    lat: r.latitude, 
    lng: r.longitude 
  }; 
});
console.log(flightPlanCoordinates);

Map iterates over each element in the original array and performs the specified function on the element, returning the result in a new array.

Comments

1
    var flightPlanCoordinates = [];
    var sales_person_route = [{'latitude':'123', 'longitude':'234'}, {'latitude':'123', 'longitude':'234'}];

    for(var i = 0; i < sales_person_route.length; i++) {

        flightPlanCoordinates.push({

            'lat': sales_person_route[i].latitude,
            'lng': sales_person_route[i].longitude,
        });
    }

console.log(flightPlanCoordinates )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.