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);
Related
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]();
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"
This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 7 years ago.
I have a question that I could not find the answer, or perhaps cannot phrase the way it should...
I would like to trick javascript's way of handling variables...
Let's say in php I could do something like:
$test['usr_'.$id]=826
But when I try to do the same in Javascript/jQuery:
$("#usr_rank_h").val('rank_'+id);
It will output rank_826 instead of the value of the var rank_826
The equivalent idiom in javascript is actually
var id = 826;
var test = {};
test['rank_'+id] = 826;
Which gives you back an object of the form
{
'rank_826': 826
}
PS: I'm not sure why you are using jQuery in this case, are you getting the id from an input ?
This question already has answers here:
is there a way to execute a function when I have its name in a string [duplicate]
(2 answers)
Closed 9 years ago.
Im not even sure how to word this and is probably why I am having trouble finding an answer in google.
When the code is run currentCardRow will equal 1 therefore it should be cardSelected1 which is what is shown in the console.log. I need it to go a step further because cardSelected1 is a variable and I need it to evaluate show in the console log as Invitation. Invitation is an example of a variable for cardSelected1.
I am not sure on what the correct syntax is to make this happen.
var currentCardSelected = "cardSelected" + currentCardRow;
Thanks for your help!
JavaScript has an Eval() function which allows you to evaluate strings as javascript code.
For example
var bar = "123";
var foo = "bar";
console.log(eval(foo));
will print "123" to the console.
For more information on eval, you can consult the MDN docs.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Generally, the use of eval() is considered poor practice as it makes the code difficult to read. There are likely more elegant solutions to implement what you have described, however, eval will solve your current problem.
var currentCardSelected = eval("cardSelected" + currentCardRow);
This is how my problem is fixed.
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.