I\'m not sure if the title is appropriate for what I am trying to achieve
I am mapping JSON results to an array. Because I need to do this over and over again I woul
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');
});