Search code examples
javascriptjquerybracketsnotation

bracket notation + javascript


This is my object :

Customer{"id": "0001", "name": "ivan" , "country" {"city" : "Peru"}}

So: Whats the correct form to use brakets? the context is in a jquery each:

$. each (datos, function (index, data) { }

1° data["country"["city"]]   >> the result should be "Peru"
2° data["country"]["city"]   >> the result should be "Peru"

or whats is the form correct?


Solution

  • I belive you are saying that your object is :

    Customer  = {
       id: "0001",
       name: "ivan",
       country: {
          city : "Peru"
       }
    }
    

    In this case your syntax would be either

    Customer.country.city
    

    or

    Customer["country"]["city"]
    

    or any mix of this two

    Note also that Customer[country[something]] can also be valid syntax, but doesnt seem to be in your case

    Customer  = {
       id: "0001",
       name: "ivan",
       country: {
          city : "Peru"
       }
    }
    
    
    country = {
       key: 'country'
    }
    
    Customer[country['key']]['city'] 
    

    would also return you city Peru