Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  150] [ 2]  / answers: 1 / hits: 75519  / 12 Years ago, fri, december 7, 2012, 12:00:00

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 would like to put the code into one function.



In the following examples I am repeating myself. I have properties called item.data1, item.data2 and in the second example item.something1, item.something2 ... How can I pass those properties as general arguments to the newly created function in order to use them there and not repeat myself to return those maps? The new function should be useable for the two examples below as well as for other cases where the properties could have different names.



service.getData(function(data) {
var map = {};
map = $.map(data, function(item, i) {
var entry = {};

entry.key = item.data1;
entry.value = item.data2;

return entry;
});
});

service.getSomething(function(data) {
var map = {};
map = $.map(data, function(item, i) {
var entry = {};

entry.key = item.something1;
entry.value = item.something2;

return entry;
});
});

More From » function

 Answers
7

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');
});

[#81555] Thursday, December 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kyrona

Total Points: 422
Total Questions: 111
Total Answers: 97

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;