Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Map via Variable Name in Path Name

Tags:

javascript

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?
like image 378
Jon Avatar asked Jan 16 '23 05:01

Jon


1 Answers

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.

like image 90
Ian Avatar answered Jan 17 '23 17:01

Ian