Search code examples
node.jseval

Converting eval to function when storing result as part of external object?


I am trying to convert some code that uses eval to use Function based on these examples, and I dont quite understand how to store the result of the function call as part of an existing object. What am I missing here?

async function test(){
  let obj={"Name":"BOB"}
  let ret={};

  //eval- works perfectly. stores the result in ret.eval
  let evalstr='ret.eval=obj["Name"].toLowerCase()'
  eval(evalstr)

  //function- 1st attempt- ret not defined
  let funcstr='ret.function=obj["Name"].toLowerCase()'
  Function('"use strict";return (' + funcstr + ')')();

  //2nd attempt-obj not defined
  let funcstr='obj["Name"].toLowerCase()'
  ret.function=Function('"use strict";return (' + funcstr + ')')();

  console.log(ret)
}

test()


Solution

  • I'm not entirely sure why you are trying to do this and I wouldn't recommend it based on the example provided. I'm positive that there is a better way achieve the desired outcome if you could provide more context.

    That said, if you want to fix the code, you need to make ret and/or obj available to the newly created Function which involves declaring them as parameters and then passing in the parameters.

    async function test(){
      let obj={"Name":"BOB"}
      let ret={};
    
      //eval- works perfectly. stores the result in ret.eval
      let evalstr='ret.eval=obj["Name"].toLowerCase()'
      eval(evalstr)
    
      //function- 1st attempt- ret not defined
      let funcstr='ret.function=obj["Name"].toLowerCase()'
      Function('ret', 'obj', '"use strict";return (' + funcstr + ')')(ret, obj);
    
      //2nd attempt-obj not defined
      funcstr='obj["Name"].toLowerCase()'
      ret.obj=Function('obj', '"use strict";return (' + funcstr + ')')(obj);
    
      console.log(ret)
    }
    
    test()