-1

I want to get the value of an object property. For reasons I wont go in to, I need the function to be abstract so i can use it in different scenarios. Here's what I have:

function getPropertyValue(obj, prop){
    return obj.prop;
}

var obj = {
    name: "tom",
    age: 23
}

console.log('age is ');
console.log(getPropertyValue(obj, "age"));

This returns underfined because it's looking for the property "prop" on the object, which doesn't exist. How do I get it to look for the property passed as prop, e.g. if "name" is passed as prop it would look for obj.name?

The jsfiddle is here

Mark
  • 4,428
  • 14
  • 60
  • 116

2 Answers2

3

Simply use bracket notation:

function getPropertyValue(obj, prop){
    return obj[prop];
}
David Thomas
  • 249,100
  • 51
  • 377
  • 410
2
function getPropertyValue(obj, prop){
    return obj[prop];
}

var obj = {
    name: "tom",
    age: 23
}

var name = getPropertyValue(obj,"name");
var age = getPropertyValue(obj,"age");
WhiteLine
  • 1,919
  • 2
  • 25
  • 53