1

I have an array that look like these: these are coordinates from an API

const paths = [
  [22.372081, 114.107877],
  [22.326442, 114.167811],
  [22.284419, 114.159510]
];

I need to convert it to something like these: with keys of lat and lng for each row.

{lat: 22.372081, lng: 114.107877},
{lat: 22.326442, lng: 114.167811},
{lat: 22.284419, lng: 114.159510}

I only have this short code but its not working what i wanted.

const waypts= [];
const paths = [
  [22.372081, 114.107877],
  [22.326442, 114.167811],
  [22.284419, 114.159510]
];
for(let i = 0; i < paths.length; i++) {
  waypts.push({
    location: new google.maps.LatLng(paths[i]),
    stopover: false,
  });
  console.log(paths[i]);
}
console.log(waypts);
1
  • Have you tried, paths.map(([lat,lng])=>({lat,lng}))? Commented Nov 2, 2020 at 12:40

3 Answers 3

3

You can use array.map() and destructure an array of arrays:

const paths = [
  [22.372081, 114.107877],
  [22.326442, 114.167811],
  [22.284419, 114.159510]
];

let result = paths.map(([lat, lng]) => ({lat, lng}));

console.log(result);

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

Comments

2

Use array destructuring with alongwith Array.prototype.map to get the result.

const paths = [
  [22.372081, 114.107877],
  [22.326442, 114.167811],
  [22.284419, 114.159510]
];

const waypts = paths.map(([lat, long]) => ({ lat, long }));
console.log(waypts);

Comments

0

It is nested array, so we can flat this array using flatMap method:

const paths = [
  [22.372081, 114.107877],
  [22.326442, 114.167811],
  [22.284419, 114.159510]
];

let result = paths.flatMap(([lat, lon]) => ({lat, lon}));
console.log(result)

Comments

Your Answer

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