Nicekiwi
Nicekiwi

Reputation: 4807

Get data from JSON query into javascript array with Array.each

I have results from a Google Geocoder request and I need a value form them to go into another array as follows:

var data = {};

Array.each(results, function(loc)
{
    data.['value'] = loc.formatted_address;
}

I need data to then contain this structure:

data = [
    {value: 'location one'}, 
    {value: 'location two'}, 
    {value: 'location three'}
];

An example of the JSON results from the query here:

http://maps.googleapis.com/maps/api/geocode/json?address=new%20york&sensor=false

In the case of the example query above the output I want is:

data = [
    {value: 'New York, NY, USA'}, 
    {value: 'Manhattan, New York, NY, USA'}
];

Im quite confused about what needs to happen in the Array.each function.

Any help would be great, thanks.

Upvotes: 0

Views: 270

Answers (1)

Paul
Paul

Reputation: 141827

Assuming results contains the results array inside the JSON object above:

var data = [];

for(i = 0; i < results.length; i++)
    data.push({'value': results[i].formatted_address});

If results contains the whole JSON object though then you need to write:

results = results.results;

before that loop.

Upvotes: 1

Related Questions