Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;     }); }); 
like image 935
maze Avatar asked Dec 07 '12 09:12

maze


People also ask

Can I pass object as parameter JavaScript?

In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.

Can you pass an object as an argument?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.

Can I pass a value or a variable as a parameter in JavaScript?

It's always pass by value (even when that value is a reference...). There's no way to alter the value held by a variable passed as a parameter, which would be possible if JavaScript supported passing by reference.


1 Answers

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'); }); 
like image 195
Alex Wayne Avatar answered Sep 24 '22 22:09

Alex Wayne