RussellHarrower
RussellHarrower

Reputation: 6810

jQuery wont turn this is into JSON

so my code I want to turn into JSON is the following

var locationData = [];
locationData['lat'] = position.coords.latitude;
locationData['long'] = position.coords.longitude;
locationData['address']['road'] = data['address']['road'];
locationData['address']['suburb'] = data['address']['suburb'];
locationData['address']['city'] = data['address']['city'];
locationData['address']['county'] = data['address']['county'];
locationData['address']['state'] = data['address']['state'];
locationData['address']['postcode'] = data['address']['postcode'];
locationData['address']['country'] = data['address']['country'];
locationData['address']['country_code'] = data['address']['country_code'];

But when I run it, It does not alert me that it has been successful

Upvotes: 0

Views: 52

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173562

Your initial declaration is wrong:

var locationData = [];

That creates an array, which will not work as you would expect; you want an object instead. You also need to initialize any complex data structure inside, such as address:

var locationData = {
    address: {}
}

Sidenote

An array is also an object in JavaScript, but it behaves in a special way when using numeric properties. In your case you're not using numeric properties at all, which is why a regular object suits your needs better.

Upvotes: 5

Chris Keele
Chris Keele

Reputation: 3455

Just as you declare the locationData as an array, you need to declare locationData['address'] as an array too. (locationData['address']=[] on your third or fourth line).

Upvotes: 0

Related Questions