0

so i have stored a JSON in a varible but how do I search it, basiclly when a user clicks the name of the business I want to load and show them the store address, phone number and other details.

here is the var

var myMarkers = {
    "markers": [
    {
        "id": 1,
        "name": "Belconnen",
        "url_name": "belconnen",
        "address": "Shop 176, 3rd Floor, Westfield Shopping Centre, Benjamin Way",
        "suburb": "Belconnen",
        "state": "act",
        "postcode": 2618,
        "country": "Australia",
        "phone": "(02) 6251 1838",
        "fax": "",
        "photo": "dcddfcb5c806b2255c611bd2d108cead.JPG",
        "text": "",
        "display": 1,
        "lat": -35.238428606,
        "lng": 149.065917134,
        "email": "[email protected]",
        "dealer_code": 63014,
        "region_id": 3,
        "type": 4
    }
]

I have removed most of the JS for easy.

This is the first time I have every tried to search and store the JS, normally i would get PHP to do it, but thought be easier and faster to get JS.

1
  • Are you able to modify the JSON? Are you generating it yourself or getting it from a third party? If it's your JSON, consider autocomplete: jqueryui.com/demos/autocomplete Commented May 25, 2012 at 2:51

2 Answers 2

1

You can access a property of an object by using object.property or object['property'] syntax (the two are synonymous, the second allows you to use an expression).

So in your case you would get the address like this:

var address = myMarkers.markers[0].address;

Use similar code to get at the other information you want.

Sign up to request clarification or add additional context in comments.

4 Comments

I understand this, however how do I do a myMarkers.markers search say I want to search for Belconnen and only show their info
@RussellHarrower - You just need to use a looping construct to loop through the JSON and use an if statement to find the property you're looking for. That's the simplest route.
You would loop through the markers - var l = myMarkers.markers.length; for( var i=0; i<l; i++) { if( myMarkers.markers[i].name == "Belconnen") { /* do stuff */ break; } }
@Kolink - Consider putting that in your answer instead of a comment, as it's more readable that way. +1 Exactly what I was thinking.
0

For searching any particular entry you can do something like this:

var target = 'Belconnen'; // value of target will change depending on click

$.each(myMarkers.markers, function() {
  if(this.name.toLowerCase() == target.toLowerCase()) {
    console.log(this.address);
    console.log(this.state); // and more
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.