2

Here I have two arrays and I need to transform first array to be in format like second array...

First array is driving directions from google map so:response.routes[0].overview_path produce something like:

An array of LatLngs representing the entire course of this route. The path is simplified in order to make it suitable in contexts where a small number of vertices is required (such as Static Maps API URLs). 

CODE

[ new google.maps.LatLng(12.34, 56.789), new google.maps.LatLng(87.65, 123.45) ] 

so I have this:

[ [56.789, 12.34], [123.45, 87.65] ] 

and I need to trasform this array with javascript in this format:

[ [ { X: 12.34 Y: 56.789 }, { X: 87.65, Y: 123.45 } ] ] 

So how I can do this? Is there any way? How to transform first array to in format like second with X and Y?

UPDATE: I do this:

tacke = response.routes[0].overview_path; rezultat = [tacke.map(function(w) { return {X:w[1], Y:w[0]}; })]; 

and now console.log(rezultat); produce this code:

console.log(rezultat); [Array[220]] 0: Array[220] [0 … 99] 0: Object X: undefined Y: undefined __proto__: Object 1: Object X: undefined Y: undefined __proto__: Object 2: Object X: undefined Y: undefined __proto__: Object 

Why here is X and Y undefinded...

DEMO:http://jsbin.com/uTATePe/41 CODE:http://jsbin.com/uTATePe/41/edit

2 Answers 2

3
var olddata = [ [56.789, 12.34], [123.45, 87.65] ] var newdata = [olddata.map(function(w) { return {X:w[1], Y:w[0]}; })]; 
Sign up to request clarification or add additional context in comments.

8 Comments

yes but there must be some "for" function, becouse this is array with approximately 200 elements...
@drCode, you probably don't know how map works: the function passed as argument is called for every item of the array, so it's an implicit "for", let's say.
Just wrap the assignment with extra brackets: var newdata = [[olddata.map(function(w) { return {X:w[1], Y:w[0]}; })]];
Is there any way to X and Y get the good values, not undefined
if your issue is that X or Y may be undefined, you can filter: [olddata.map(function(w) { return {X:w[1], Y:w[0]}; }).filter(function(w) { return typeof w.X !== "undefined" && typeof w.Y !== "undefined"})];, although it's not obvious to me why you would have undefined values in the first place (is google maps sending you bad data?)
|
2

If you absolutely must use a for loop, this will create the data structure you want. I still recommend Nirk's solution.

var data = [ [56.789, 12.34], [123.45, 87.65] ]; var result = [[]]; for(var i = 0; i < data.length; i++) { result[0].push({"X": data[i][0], "Y": data[i][1]}); } console.log(JSON.stringify(result)); 

JSFiddle

2 Comments

Use case for above: Array.prototype.map is not supported in IE8.
@Robusto you can implement it directly if it is not available: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.