Access variable property by Name as String ?

If i have a javascript object that looks like below

var employee = {
  job: programmer,
  address : India,
  status : single

and i have a function that is passed both the object, and a property name like so

//should return false

var person = read_prop(employee, 'status');

what would the body of read_prop(object, property) look like?

You don’t need a function for it – simply use the bracket notation:

var person = employee['status'];

This is equal to dot notation,

 var person = employee.status;

, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];

More Info: Bracket Notation</strong>


My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Snippets Tagged with: ,