Question

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?

Was it helpful?

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

OTHER TIPS

This is not an JavaScript object:

Customer[id: "0001"; name: "ivan" ; country [city : "Peru"]]

This is an object in JavaScript object:

var customer = {
   id: "0001",
   name: "ivan",
   country: {
      finland: {
         city: "Helsinki"
      }
   }
};

You would use it with this:

console.log(customer.country.finland.city);

or this:

console.log(customer['country']['finland']['city']);

or with mixing....

console.log(customer['country'].finland.city);

..and yes took a freedom of adding actual country, not just city but I guess this post demonstrates the point, you can either retrieve values with dot notation customer.country.finland or apostrophes customer['country']['finland'] .. However, if you are using numbers as JavaScript object key like this:

var customer = {
  1: "Mauno"
};

You can retrieve it only using apostrophes as: customer['1'] trying to use it like customer.1 will result in a JavaScript error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top