0

I want to convert an array to object with key-value pairs.

The array is like this:

latLngArray = [ '52.12,-106.65', '53.53,-113.50' ]

I want to convert it to array of objects like this:

[{lat: 52.12, lng: -106.65}, {lat: 53.53, lng: -113.50}]

I tried to separate each element in the array with split but didn't help.

How can I convert this array to an object?

0

1 Answer 1

5

Try this with simple map()

latLngArray = ['52.12,-106.65', '53.53,-113.50'];
result = latLngArray.map(coords => {
  const [lat, lng] = coords.split(',');
  return {
    lat,
    lng
  };
});

console.log(result)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. How can I apply parseFloat to your solution to convert the numbers to float?
Consider doing const [lat, lng] = coords.split(',').map(Number)
return {lat: parseFloat(lat), lng: parseFloat(lng)};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.