-2

After a mysql query, I used the json_encode to convert the result of the query and I'm getting the following:

[
    {"id":"1","map_id":"1","description":"This is Athens","lat":"37.77994127700315","lng":"23.665237426757812","title":"Athens"},
    {"id":"2","map_id":"1","description":"This is Rome","lat":"41.9100711","lng":"12.5359979","title":"Rome"}
]

I want to convert this to JavaScript array but getting only the values. For example:

myArray = [  
    [1, 1, 'This is Athens', 37.77994127700315,23.665237426757812, 'Athens']
    [2, 1, 'This is Rome', 41.9100711, 12.5359979, 'Rome']
]

I tried many solutions I found here, but I didn't found any solution to give me exactly an array like myArray.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Maria Kypr
  • 41
  • 2
  • 8

1 Answers1

0

Assuming :

var a = [{"id":"1","map_id":"1","description":"This is Athens","lat":"37.77994127700315","lng":"23.665237426757812","title":"Athens"},{"id":"2","map_id":"1","description":"This is Rome","lat":"41.9100711","lng":"12.5359979","title":"Rome"}];

You can use Array.prototype.map():

var myArray = a.map(function(e){
    return [e.id, e.map_id, e.description, e.lat, e.lng, e.title];
});

Result:

[
  ["1","1","This is Athens","37.77994127700315","23.665237426757812","Athens"],
  ["2","1","This is Rome","41.9100711","12.5359979","Rome"]
]
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • How can I check the contents of myArray? I used alert(JSON.stringify(myArray)). Is this right? – Maria Kypr Nov 03 '14 at 13:44
  • Yea, that works, although I prefer using the developer console with `console.log(myArray)` – Cerbrus Nov 03 '14 at 13:46
  • I'm getting the following error : Uncaught TypeError: undefined is not a function for line var myArray = a.map(function(e){ – Maria Kypr Nov 03 '14 at 14:00
  • So, @MariaKypr, did this help you? – Cerbrus Nov 03 '14 at 15:43
  • Yes, but unfortunately this returns a result ["1","1","This is Athens","37.77994127700315","23.665237426757812","Athens","2","1","This is Rome","41.9100711","12.5359979","Rome"]. It results in array with one row. – Maria Kypr Nov 04 '14 at 07:56
  • Eh, no, it doesn't. I added the result to my answer. You are probably overlooking some brackets. In fact, the result you describe can't possibly be the result from my code. – Cerbrus Nov 04 '14 at 08:01
  • 1
    I found what was wrong. In my code, I used jQuery ajax to make a call to php function. The php function results to the json_encode and it was returned to ajax from "success" parameter. The result was returned as a string, not as an object. I used JSON.parse() to convert it to json object and now it's working! :) Thank you!! :) – Maria Kypr Nov 04 '14 at 08:38