Home > Software design >  How I can deal with outside commas from java-script
How I can deal with outside commas from java-script

Time:06-29

I'm facing a problem, flask app is returning an array in this form "['Aliens vs Predator: Requiem', 'Aliens', 'Anne of Green Gables']", but when I tried to access 0 index(first index), only [ this bracket prints on "demo" id;

So I have to remove outside commas of arrays so that I will get this result: ['Aliens vs Predator: Requiem', 'Aliens', 'Anne of Green Gables']. I didn't have any idea to do this, anybody can help me,

<!DOCTYPE html>
    <html>
    <body>
    
    <h2>Declaring an Array</h2>
    
    <p id="demo"></p>
    
    <script>
    
    var movies = "['Aliens vs Predator: Requiem', 'Aliens', 'Anne of Green Gables']";
    document.getElementById("demo").innerHTML = movies[0];
    
    </script>
    
    </body>
    </html>`

CodePudding user response:

You can parse your data this way (the JSON parser doesn't like single quotes):

var movies = "['Aliens vs Predator: Requiem', 'Aliens', 'Anne of Green Gables']";
let data = JSON.parse(movies.replaceAll('\'',"\""))
console.log(data[0])

CodePudding user response:

Just remove double quotes from "movies" variable. it should look like this:

let movies = ['Aliens vs Predator: Requiem', 'Aliens', 'Anne of Green Gables'];
  • Related