0

is there a way to dynamically set a parameter, or property for a function in javascript? some examples:

const funcOne = (param1, param2) => console.param1(param2);

funcOne(log, `hello there`);

obviously the above doesnt work, just bring an example, same as below:

const mongoFunc = param, filter => Collection.param(filter, (err, foundArticle) => {
// code block
});

this will work:

const funcOne = (param1, param2) => console.log(param1, param2);
funcOne(`hello`, `there`);

so I was wondering if theres a dynamic way to set the log in console.log same as when it comes to mongo to dynamically set Collection.find or collection.findOneAndUpdate.

Thank you in advance.

Dmitriy Z
  • 35
  • 5
  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – shkaper Jul 05 '20 at 03:00
  • Is "currying" what are you looking for, maybe? https://javascript.info/currying-partials – shotasenga Jul 05 '20 at 03:08

2 Answers2

1

You'll first of all have to pass log as a string because otherwise it will throw an error saying log is undefined.

You can try this:

const funcOne = (param1, param2) => console[param1](param2);
funcOne('log', `hello there`);

If you want to dynamically access an object's property in javascript you have to use square bracket notation.

Hope this helps!

Tushar
  • 665
  • 5
  • 11
1

Yes, you can definitely do it. First of all, in an object, you can access/create a dynamic key using [] as in:

object[dynamicKey] = 'someVal';

where the dynamicKey string is a key you want to access in an object. Example

const sampleObject = {
   name: 'stack',
   flow: true,
};

const setDynamicKey = (o, k, v) => (o[k] = v);

setDynamicKey(sampleObject, 'hello', 'world!');
console.log(sampleObject); // { name: 'stack', flow: true, hello: 'world!' }

Now for your case, you can do something like

const funcOne = (param1, param2) => console[param1](param2);

funcOne('log', 'hello there');
jfriend00
  • 683,504
  • 96
  • 985
  • 979
folan
  • 215
  • 1
  • 8