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"
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 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);
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"
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:
"Variable" variables in JavaScript
(9 answers)
Closed 9 years ago.
I can't figure out how to use the name of a variable previously created with eval, without knowing it.
I mean:
function getName(menu_name, level){
eval("var menu_"+level+"="+menu_name);
}
Now how do I get the name of the variable I just created? Probably keep using eval, but I have to put that name into a $.post call as one of my field name.
Thanks in advice.
If level is an integer, you can treat it as a numerical index for an array:
var menu = [];
menu[level] = menu_name;
If level is anything else, you can treat it as a key for a dictionary/associative array:
var menu = {};
menu[level] = menu_name;
Then, for either of the solutions, if you want to access your menu_name, simply call menu[level].