-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
  • 20,490
  • 40
  • 124
  • 179

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
  • 13,561
  • 4
  • 49
  • 70
0
function getProperty(obj,property){
  return obj[property].value;
}
sjm
  • 5,248
  • 1
  • 25
  • 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
  • 756,363
  • 169
  • 1,062
  • 1,111
Nabin Singh
  • 377
  • 2
  • 6