0

Possible Duplicate:
Dynamic object property name

I have an object like this

var localAppConfig = {
    wallet:0,
    paySomeone:0,
    payBills:0,
    accounts:0,
    moveMoney:0,
    alerts:0,
    offers:0,
    checkIn:0
};

I want to set value 1 for particular elements within this localAppConfig

Which element needs to be set is retrieved from the json - which arrives from the server.

say, I want to set value = 1 for wallet, paySomeone, payBills, alerts, offers, checkIn

These are retirved from the json like

for(var i=0;i<len;i++){
        var name = list[i].handle;
        var accessor = eval('localAppConfig.'+name);
        eval('localAppConfig.'+name)=1;
    }

var name contains name of the element and I am able to access its value correctly,

How can I set the value using javascript?

I tried accessor=1 but its not working.

Thanks :)

Community
  • 1
  • 1
AdityaParab
  • 7,024
  • 3
  • 27
  • 40

4 Answers4

3

You should do this instead:

var accessor = localAppConfig[name];
localAppConfig[name] = 1;
James M
  • 18,506
  • 3
  • 48
  • 56
3

Anyhow: try this on for size:

localAppConfig[name] = 1;//where name is a variable of choice, it's value will be used as the propertyname

And again:

-When all you have is the eval hammer, everything looks like your thumb. –Brendan Eich in response to: we should encourage use of eval() rather than the Function constructor for dynamic creation of functions.

But why use a list of the properties? you might as well use a for...in loop: in case of objects, like yours, it's perfectly all right.
As long as you check .hasOwnProperty, too:

for (var prop in localAppConfig)
{
    if (localAppConfig.hasOwnProperty(name))
    {
        //set, delete... do whatever
    }
}
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
1

Try localAppConfig[name] = 1;

It's just a javascript object, no need to use eval() on it.

A Person
  • 1,350
  • 12
  • 23
0

Don't use eval(). You can add a property by referencing the index of that value within your object. If it doesn't exist then it will be created, otherwise the value will be overridden.

Try the following instead:

// localAppConfig[list[i].handle] = 1; 

for(var i=0;i<len;i++){         
    localAppConfig[list[i].handle] = 1;
} 

Or if you intend to reference the variable in another place then set a variable with the value of list[i].handle:

for(var i=0;i<len;i++){
    var name = list[i].handle;        
    var accessor = localAppConfig[name];    
    localAppConfig[name] = 1;
} 
Robert
  • 8,717
  • 2
  • 27
  • 34