3

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 1

6

You 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);
Sign up to request clarification or add additional context in comments.

2 Comments

@Répás - Not at all - I've asked this same question before when I was learning :)
yep, i using extend simply forgot this method bah. ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.