Turn a string into function in JS [duplicate] - javascript

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
My problem is simple and I couldn't find the proper answer in this forum. My bad...
I want to do that :
const dataReceived = foo;
foo(state);
How can I do that?
I read it is better to avoid eval, and I couldn't get success with new Function.
Thanks for your help!
EDIT
Thanks for your answers.
I work with React.
In my reducer, I have a create_item case.
I can reach action.category, that can be the word 'currency' or 'country'.
What I want to do is to launch either the method createCurrency or createCountry according what is inside action.category.
That's why I tried to join 'create' and 'action.category' to create a dynamic function name.
But it seems to be a poor idea...

The simplest approach is to create an object which contains an entry where:
the key is a string
the value is a function.
Example:
const myObject = {
myFunction: () => { [... DO SOMETHING...] }
}
Subsequently you will be able to invoke the function, using:
myObject.myFunction();
The above becomes more powerful when you use brackets notation.
Example:
const myString = 'myFunction';
myObject[myString]();

Related

How to add item to object JS [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I have looked all over google and i have found nothing that fits my needs. How would you add an item to an object. I basically have a string variable that i want as the key. Therefore i cant use obj.key = 'something';. I sort of want it like:
obj = {'somekey': 'somevalue'};
obj.add('someotherkey': 'someothervalue');
console.log(obj);
by obj.add() i mean someone's solution
and then console says {'somekey': 'somevalue', 'someotherkey': 'someothervalue'}
Does anyone know a way to do this. I don't care at what position it is just whether it is there. By the way i'm using node if that helps. If you have any questions on my code please ask.
Very simple:
obj["somekey"] = "somevalue";
You can also use a variable instead:
let myVariable = "somekey";
obj[myVariable] = "somevalue";
Or you just use normal object notation:
obj.somekey = "somevalue"

How to create a function that can be called on an object in javascript [duplicate]

This question already has answers here:
Add method to string class
(6 answers)
Closed 4 years ago.
So, for learning purposes I'd like to recreate the "charAt()" existing method in Javascript which tells you the position of a character in a given string. I'll call the method "CharAtX"
To do so, I've created a function with 2 parameters : The first one is the word, the second is the position, here is the code I have :
function charAtX(word,pos) {
word_split = word.split("");
return(word_split[pos])
}
console.log(charAtX("Truck",2))
So, it obviously works, if i call charAtX("truck",2), i will have "u" returned.
But my question is the following :
The original charAt can be called like such
my_word.charAt(3)
Mine can't though. Why is that and how could I change my function into a method so that I can?
You have to call charAtx function in the context of String object.So, When you call string.charAtx, this object refers to the string. You have to learn prototype and this object in jvascript.
String.prototype.charAtX = function(pos) {
word_split = this.split("");
return(word_split[pos])
}

Really basic javascript function concept [duplicate]

This question already has an answer here:
How do I access an object property dynamically using a variable in JavaScript?
(1 answer)
Closed 5 years ago.
Testing my ability to write code in JavaScript and Node (perhaps a bit of a monumental effort) and also attempting to understand standards.
I want to dynamically change an attribute in an object as in this examnple:
var parms = {
host:'',
port:'',
user:'',
pass:''
};
parms.user='foo';
parms.pass='bar';
console.log(parms.user);
setParm = function(param,value){
parms.param = value;
}
setParm('user','baz');
console.log(parms.user);
However, I'm completely blind. I feel as though I may be in a blind alley in terms of what I think is possible versus what is actually workable.
You are passing the property as a string, so accessing with . won't work. One solution I know is that you can use dict-like indexing:
var parms = {
host:'',
port:'',
user:'',
pass:''
};
parms.user='foo';
parms.pass='bar';
console.log(parms.user);
setParm = function(param,value){
parms[param] = value;
}
setParm('user','baz');
console.log(parms.user);

Given the path of property key, how to retrieve it? [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Javascript: Get deep value from object by passing path to it as string [duplicate]
(5 answers)
Closed 5 years ago.
Consider I've an object myObj
And I've a string representing the path to some property inside it: foo.bar
What is the best way to get it from my object?
If I knew the string ahead I would do myObj.foo && myObj.foo.bar to get it safely
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
But i'm sure there is a better way
It's a duplicate of other question. they provided a great solution:
given a path and an obj get the property value this way
path.split('.').reduce((o, i) => o[i], obj)
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
Yep, that sounds like the best way. You can create a helper method that does exactly this, but there's nothing built in to the language or standard libraries to make things simpler than this.
function getFromPath(obj, path) {
var current = obj;
for(let piece of path.split('.')) {
current = current[piece];
}
return current;
}
Usage:
getFromPath({foo: {bar: "hello"}}, "foo.bar"); // "hello"

Is it possible to make User defined DOM changes in runtime? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript object, access variable property name?
I am messing around with JS, learning a stuff and I am wondering about something...
Say you have a function aFunc(), and you accept a string aFunc(val). The value is user defined and is then used to modify the CSS of an element.
For Example:
function aFunc(val){
document.getElementById('something').style.val = 'red';
}
Say the user entered borderColor, it would somehow refrence borderColor where val is. I do not know how or if this is possible.
EDIT:
Please no eval() :)
Just use this as a base: JSBIN- Demo on a Div
var type = prompt("style");
var value = prompt("value");
document.body.style[type] = value;
Every object in JavaScript has a method called hasOwnProperty which takes a string value and will return a Boolean value.
var myObj = {
name: "Josh"
};
myObj.hasOwnProperty("name") === true; //This is true
You can use that to test for the presence of a particular property and then use the method stated in Akhil Sekharan's answer to access that property.

Categories