There is an array of valid:

var points = [[52.0625,142.962494],[52.0625,143.129166],[52.054165,142.995834],[52.054165,143.079163],[52.054165,143.145828], ...] 

I run through the loop and take only the values ​​and put them in the object:

  $.each(points, function(k, v){ var myArray = []; var myObject = { "lat": v[0], "lon": v[1] } }); 

There is also an empty array

 var myArray = []; 

in this scenario:

 myArray.push(myObject); console.log(myArray) 

Output:

[Object] [Object] [Object] [Object] [Object] [Object] [Object] ...

And I need to put all the objects in the empty array myArray = []; so that consol.log would output like this:

 [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …] 

I can not understand where my mistake? Tell me please. Thanks in advance!!!

    2 answers 2

    The myArray declaration needs to be moved out of the function to each , because now you have a new array created at each step of the loop, which ultimately contains only one element, and which is not accessible outside the loop:

     var points = [ [52.0625, 142.962494], [52.0625, 143.129166], [52.054165, 142.995834], [52.054165, 143.079163], [52.054165, 143.145828] ], myArray = []; $.each(points, function(k, v) { var myObject = { "lat": v[0], "lon": v[1] }; myArray.push(myObject); }); console.log(myArray); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    • “Outside” the function , not the loop. You can simply remove the array declaration inside the function in the TS code, and the code will work. - Sergiks
    • Thank you very much!!! A trifle like I broke my head))) - mikhailir

    Konstantin answered the direct question about where the error is in your code.

    I will add that your task is more elegant to solve a little differently: use the standard .map() method - the function inside will be applied to each element of the array, and you will immediately get a new array with “converted” elements:

     var points = [[52.0625,142.962494],[52.0625,143.129166],[52.054165,142.995834],[52.054165,143.079163],[52.054165,143.145828],]; var myArray = points.map( function(el){ return { lat: el[0], lon: el[1] }; }); document.body.innerHTML = JSON.stringify( myArray); 

    This is pure JavaScript, does not require additional. libraries like jQuery. In jQuery there is a similar method , it is not necessary to complicate, but for general development, it is possible and so:

     // изменения только в этой строке: var myArray = $.map(points, function(el){ 
    • Cool!!! Thank you very much!!! - mikhailir