-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.

3

1 Answer 1

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"]
]
7
  • How can I check the contents of myArray? I used alert(JSON.stringify(myArray)). Is this right? Commented Nov 3, 2014 at 13:44
  • Yea, that works, although I prefer using the developer console with console.log(myArray) Commented Nov 3, 2014 at 13:46
  • I'm getting the following error : Uncaught TypeError: undefined is not a function for line var myArray = a.map(function(e){ Commented Nov 3, 2014 at 14:00
  • So, @MariaKypr, did this help you? Commented Nov 3, 2014 at 15:43
  • 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!! :) Commented Nov 4, 2014 at 8:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.