Vivek Vardhan
Vivek Vardhan

Reputation: 1178

Avoiding eval() in a particular scenario

I have read at several places that we should avoid using eval in our JavaScript code. But, i have a scenario, i am not able to remove this. need help with that

        var levels=[];
        for(var k=0;k<levels.length;k++){
            var levelsArray={};
            levelsArray["name"]=levels[k].name;
            levelsArray["caption"]=levels[k].caption;
            var prop = levels[k].name;
            eval("levelsArray[\"memberProvider\"]= function (item) { return item." + prop + ";}");
            levels.push(levelsArray);
        } 

I hope, the code is clear in what i am trying to do.

Upvotes: 0

Views: 53

Answers (1)

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

levelsArray.memberProvider = (function(p) {
  return function (item) { return item[p]; };
})(prop);

Upvotes: 4

Related Questions