-1

I have this code

let route = res.data.data;
console.log('data to be loop: ', route)

var ddd = [];
for(let i = 0; i < route.length; i++){
  ddd = [...route[i].longitude, ...route[i].latitude]
}
console.log('final data: ', ddd)

The result of code above is:

one

What I'm trying to do is to get longitude, latitude of each row and place them as separate array into ddd array. something like this:

ddd = [
  0: {
     lat: xxxxx,
     lng: xxxxx
  },
  1: {
     lat: xxxxx,
     lng: xxxxx
  }
]

What should I change in my code to achieve that?

4
  • since those properties are not arrays, you wouldn't use ...route[i].longitude - more like ddd.push({lat:route[i].latitude, lng:route[i].longitude} - or better yet var ddd = route.map(({longitude:lng, latitude:lat}) => ({lng, lat})); Commented May 14, 2020 at 3:57
  • can you paste your json instead of snapshot Commented May 14, 2020 at 3:58
  • ...route[i].longitude is spreading each character of the latitude and longitude string to the array and it is being replaced in each loop Commented May 14, 2020 at 3:59
  • @adiga what should i do? Commented May 14, 2020 at 4:00

2 Answers 2

2

Use JavaScript map function. Your code would become:

let route = res.data.data;

const ddd = route.map((element) => {
  return {
    lat: element.latitude,
    lng: element.latitude,
  };
});

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

Comments

1

Use Array.map:

let route = res.data.data;
console.log('data to be loop: ', route)

let ddd = route.map(x => {
    return {
        lng: x.longitude,
        lat: x.latitude
    }
})

console.log('final data: ', ddd)

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.