How to pass an object property as a parameter? (JavaScript)

use [] with a string to pull out properties from objects dynamically.

var a = { foo: 123 };
a.foo    // 123
a['foo'] // 123

var str="foo";
a[str]   // 123

Which means we can refactor your method like so, just pass in the names of the properties you want to read as strings.

var getKeyValueMap = function(data, keyPropName, valuePropName) {
  return $.map(data, function(item, i) {
    return {
      key:   item[keyPropName],
      value: item[valuePropName]
    }
  });
};

service.getData(function(data) {
  return getKeyValueMap(data, 'data1', 'data2');
});

service.getSomething(function(data) {
  return getKeyValueMap(data, 'something1', 'something2');
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)