I would like to replace a variable in an object, but without knowing the variable's key... eg.:
var parameters = new Object();
parameters.startregion = null;
parameters.fx_adultnum = 2;
... bit later
$adultnum.change(function(){ setParameters("fx_adultnum", $adultnum.val() );});
and the setParameters function (what is absolutely don't work :P
function setParameters(v, value){
console.log(parameters);
$.each(parameters, function(key, val) {
if (key == v) {
console.log(key);
console.log(val);
$(this).val(value); // <-- not works
}
});
console.log(parameters);
}
I would like to replace fx_adultnum's value to 4 for example.
Could you help in this for meh? Thanks much.
I would like to replace a variable in an object, but without knowing the variable's key... eg.:
var parameters = new Object();
parameters.startregion = null;
parameters.fx_adultnum = 2;
... bit later
$adultnum.change(function(){ setParameters("fx_adultnum", $adultnum.val() );});
and the setParameters function (what is absolutely don't work :P
function setParameters(v, value){
console.log(parameters);
$.each(parameters, function(key, val) {
if (key == v) {
console.log(key);
console.log(val);
$(this).val(value); // <-- not works
}
});
console.log(parameters);
}
I would like to replace fx_adultnum's value to 4 for example.
Could you help in this for meh? Thanks much.
1 Answer
Reset to default 6You can access an object's property by name with a simple index:
this[val] = value;
Just note that in $.each
the this
context is set to the value you're currently iterating. Did you really mean:
v[key] = val;
You might also look at jQuery's extend function
var A = { "x": 1, "y": 2 };
var B = { "y": "3", "z": 12 };
$.extend(A, B);
now A is { "x" : 1, "y": "3", "z": 12 }
Or if you want to get this same result, without modifying A, then you could do:
var newObj = $.extend({}, A, B);