1

I've been searching all over SO and I know there are a lot of topics about this but I haven't found one that answered my question.

I saw a question about getting an object value back from a string like this:

function getPropertyByString(str) {
    var properties = str.split(".");
    var myTempObject = window[properties[0]];
    for (var i = 1, length = properties.length; i < length; i++) {
        myTempObject = myTempObject[properties[i]];
    }
    return myTempObject;
}

So if there is a global variable called myGlobalVar, you could pass the string 'myGlobalVar.someProp.stateName' and assumming that is all valid you would get back the value of stateName say Arizona for example.

How could I update that property to California now?

If I try

var x = getPropertyByString('myGlobalVar.someProp.stateName');
x = 'California';

that will update the value of x and not the object.

I tried

var x = getPropertyByString('myGlobalVar.someProp.stateName');
x.value = 'California';

that didn't work either.

Can someone please help me to understand this with my example?

Thanks

blong824
  • 3,920
  • 14
  • 54
  • 75

2 Answers2

3

Try the following;

function setPropertyByString(path, value) {
    var steps = path.split("."),
        obj = window,
        i = 0,
        cur;

    for (; i < steps.length - 1; i++) {
        cur = obj[steps[i]];

        if (cur !== undefined) {
            obj = cur;
        } else {
            break;
        };
    };

    obj[steps[i]] = value;
}

It'd work by using it such as;

setPropertyByString('myGlobalVar.someProp.stateName', 'California');

You can see it in action here; http://jsfiddle.net/xCK8J/

The reason yours didn't work is because strings are immutable in JavaScript. You are re-assigning the variable x with the value 'California', rather than updating the location it points to to be 'California'.

If you'd have done;

var x = getPropertyByString('myGlobalVar.someProp');
x.stateName = 'California';

You'd see it works; as you're manipulating the object pointed to by x, rather than reassigning x to be something else. The above is what the setPropertyByString() method does behind the scenes; it just hides it from you.

Matt
  • 74,352
  • 26
  • 153
  • 180
2

This would do the trick:

myGlobalVar.someProp.stateName = "California"

So would this:

myGlobalVar["someProp"].stateName = "California"

or this:

myGlobalVar["someProp"]["stateName"] = "California"

Alternatively,

var x = getPropertyByString('myGlobalVar.someProp');
x.stateName = "California"

Note that if, in my last example, I do something like this:

x = {stateName:"California"};

It will not change the value of myGlobalVar.someProp.stateName.

Using = assigns a new value to the variable on the LHS. This is not the same thing as assigning a new value to the referent of the variable.

Paul Butcher
  • 6,902
  • 28
  • 39