-1

Imagine I have an object like:

var obj = {
  name: {
    value: 'Sergio'
  },
  lastName: {
    value: 'Tapia'
  }
}

I want to create a function that grabs the value of a given property.

Ideally:

console.log(getProperty(obj, 'name'));
=> 'Sergio'

console.log(getProperty(obj, 'lastName'));
=> 'Sergio'
sergserg
  • 21,716
  • 41
  • 129
  • 182

3 Answers3

2

You can use bracket notation to access the property on the object. Your function would be:

function getProperty(obj, property) {
  return obj[property].value;
}

I would probably name it getProperyValue instead.

Cymen
  • 14,079
  • 4
  • 52
  • 72
0
function getProperty(obj,property){
  return obj[property].value;
}
sjm
  • 5,378
  • 1
  • 26
  • 37
0

This function should help you achieve what you need.

function getProperty(obj, key){
  return obj[key].value;  
}

I believe

console.log(getProperty(obj, 'lastName'));

should return 'Tapia' rather than 'Sergio'.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Nabin Singh
  • 377
  • 2
  • 6