开发者

Set a variable variable on an object in javascript

Doing some work with Omniture analytics and want to be able to set some properties via JSON.

Omniture calls look something like this:

s.linkTrackVars = 'eVar37';
s.eVar37='foo';
s.tl(true, 'o');

I want to write开发者_运维技巧 a generic function to take a JSON object and convert it into those variables. AFAIK Omniture doesn't allow you to simply pass it JSON, so this the only method I can think of.

Here's the example of the JSON structure I want to use:

var omniture = {

    "evars":
    [
        {
            "key": "37",
            "value": "foo"
        },

        {
            "key": "32",
            "value": "bar"
        }
    ]

}

My function to work with this JSON looks like this:

for (i in omniture.evars) {
    var evar = omniture.evars[i];
    window[s.eVar + evar.key] = evar.value;
}
alert(s.eVar37); // alerts "undefined"

If I do this, it works:

for (i in omniture.evars) {
    var evar = omniture.evars[i];
    window['eVar' + evar.key] = evar.value;
}
alert(eVar37); // alerts "foo"

It seems that I can't set a variable variable as a property of an object (eg s.eVar37 as opposed to evar37). Can anybody think of a nice way of setting these variables automatically?

thanks, Matt


Sure you can. Just set it on s directly:

s['eVar' + evar.key] = evar.value;


IIUC you want s['eVar' + evar.key] = evar.value;.

edit: alternative

It would be simpler though to just have

var omniture =
{
    evars:
    {
        "37": "foo",
        "32": "bar"
    }
}

copyFromInto(omniture.evars, 'eVar', s);

function copyFromInto(o1, prefix, o2)
{
    for (var i in o1)
    {
         o2[prefix + i] = o1[i];
    }
}

alert(s.eVar37); // alerts "foo"

But of course it all depends on what you want to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜