Hailwood Hailwood - 1 year ago 67
Javascript Question

JavaScript object: access variable property by name as string

If I have a javascript object that looks like below

var columns = {
left: true,
center : false,
right : false

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

//should return false
var side = read_prop(columns, 'right');

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

Answer Source

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, 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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download