There is an array of objects. Each object has coordinates. Nesting levels are different, as is the number of pairs of coordinates. The problem is that they are suitable for creating layers, and to follow the link, these coordinates need to be reversed (reverse (), for example). How to set a cycle so that it goes through all pairs of coordinates and swaps them?

var ao=[ { "type": "Feature", "properties": { "NAME": "Центральный", "ABBREV": "ЦАО" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 37.51393, 55.75842 ], [ 37.51567, 55.75909 ] ], [ 37.51927, 55.76047 ], [ 37.51993, 55.76072 ], [ ... ] ... ]] } }, и т.д. ] 

    2 answers 2

    duck you break the task into steps. First, you need to recurse bypass the array. Secondly, you need a sign of the end of recursion, in which you need to determine that the array has two elements, and these are numbers (it's enough to check first).

     var data = [ [ [ 1, 2 ], [ 3, 4 ] ], [ 5, 6 ], [ 7, 8 ], ]; function mapper(v){ if(v.length == 2 && typeof v[0] == 'number'){ return [v[1], v[0]]; } return v.map(mapper); } var result = data.map(mapper); console.log(result); 

      As an option (transfer the coordinates object to the function):

        function reverse(array) { var lat, lng; array.forEach(function (item, index) { if (Array.isArray(item)) { reverse(item) } else { index === 0 && (lat = item); index === 1 && (lng = item); } }); if (lat && lng) { array[0] = lng; array[1] = lat; } }