0

I have a JSON in the below format

waypoints = [
{
lat: 22,
lng: 44
},

{
lat: 55,
lng: 77
}

]

I need to convert it into the following format using JS

[[22, 44], [55, 77]]

Please can some one help me with a solution

2
  • 4
    Have you even tried searching for a similar question? Commented Aug 28, 2015 at 12:15
  • 1
    There is no JSON in your question. That's an array initializer containing object initializers. If you're in JavaScript source code, you're not dealing with JSON (unless it's inside a string). Commented Aug 28, 2015 at 12:22

5 Answers 5

4

Just use map.

var foo = waypoints.map(function(waypoint){
  return [waypoint.lat, waypoint.lng];
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can create a new array with use of .map method which in execution creates a new array without modifying the original array:

var waypoints = [{
  lat: 22,
  lng: 44
}, {
  lat: 55,
  lng: 77
}];

var newArr = waypoints.map(function(obj) {
  return [obj.lat, obj.lng];
});

document.body.textContent = JSON.stringify(newArr);

3 Comments

I recommend to read this to understand how .map() works and what it is meant for
@Andreas true! i always miss about .map() method.
@RGraham I will take care of that now on.
1

You can use for...in loop and get the array

var array=[];

for(var i =0;i< waypoints.length;i++){
var nestedArray=[];
  for(var key in waypoints[i]){
      nestedArray.push(waypoints[i][key])
    }
   array.push(nestedArray)
 }

Found other answers using map functionality of JavaScript. Thats good!!!

Comments

0
var waypoints = [
    {
        lat: 22,
        lng: 44
    },
    {
        lat: 55,
        lng: 77
    }
];
var array = [];
for (i in waypoints) {
    array.push([]);
    for (j in waypoints[i]) {
        array[i].push(waypoints[i][j]);
    }
}

1 Comment

Welcome to Stack Overflow! Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.
0
You can use:
    waypoints = [{lat: 22, lng: 44   }, { lat: 55, lng: 77   } ];
     var innerArr = [];
     var requiredArray = [];
     for (var i = 0; i < waypoints.length; i++) {
         innerArr = [];
         innerArr.push(waypoints[i].lat);
         innerArr.push(waypoints[i].lng);
         requiredArray.push(innerArr);
     }

Comments

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.