I have a map object containing a list of data about people. Every person's name is unique. The data fields of each person may not contain the same type of information (ie - Joey contains a date field, but Jill does not).
I am wondering if I can access a certain part of my map by using a variable name as part of the map path. Consider the following:
var data = {
'Joey': {
'id': '912',
'date': 'May 14 2012',
},
'Jill': {
'id': '231',
'login': 'JillM',
}
}
var name="Joey";
var joeyDate = data. + name + .date; //This does not work. Is there an alternative?
Use this syntax:
data[name]["date"]
This is an alternative to data.Joey
, which should also work, but is static.
You can also use:
data[name].date
The difference is exactly what you're inquiring about - []
notation is better for dynamic retrieval and possibly invalid keys that wouldn't be allowed with Javascript if using dot notation. For example, if you had a key of "date-born", you can't use data[name].date-born
, but you can use data[name]["date-born"]
.
An example of using this is:
for (name in data) {
console.log(data[name].date);
}
But of course, date
must be a property (where it isn't for "Jill"), otherwise undefined
will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With