Search code examples
javascripteval

How to use eval() to assign one object to another


Disclaimer: I know you are supposed to not use eval() but I wouldn't if I had any other choice in my situation. This, you must trust.

Why does this code below throw a error and how can I make an equivalent expression?

let r = ".b.b = a.b.b"
let l = {b:{b:5}}
let a = {b:{b:0}}
l.toString()
alert(eval(l+r))


Solution

  • One thing that is causing you an error is that your l.toString() call is returning the string "[Object object]".

    Try using l = JSON.stringify(l) instead.

    Although, to make your code snippet work, you need to omit stringifying l altogether. Instead reference l as just the string "l" to make the eval work as expected.

    let r = ".b.b = a.b.b"
    let l = {b:{b:5}}
    let a = {b:{b:0}}
    console.log(eval("l"+r))