javascriptarraysstring

Convert a JavaScript statement to a string


I have an array in a variable like:

arr = [1, 2, 3]

How can I convert that statement to a string that it will be:

newArr = "arr = [1, 2, 3]"


Solution

  • Try this:

    const arr = [1, 2, 3];
    
    const str = `${Object.keys({arr})} = ${JSON.stringify(arr)}`;
    
    console.log(str);

    References:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify