Home > Mobile >  JavaScript - get 'i'th element of list trough Flask
JavaScript - get 'i'th element of list trough Flask

Time:10-24

I'm working in an HTML file. I have a list of dictionaries that I got trough Flask from my Python document. I'm trying to loop over each element of the list in JavaScript and getting a the value. What I tried these solutions but they didn't work:

```for (let i = 0; i < 6; i  )
{
var value = '{{data[i]["key"]}}'
//do some stuff with it.
}```

Error:

File "/home/ubuntu/final_project/templates/results2.html", line 144, in top-level template code var stuff = {{data[i]['key']}} File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 452, in getitem return obj[argument] jinja2.exceptions.UndefinedError: list object has no element Undefined

And without the quotes around the double braces:

```for (let i = 0; i < 6; i  )
{
var value = {{data[i]["key"]}}
//do some stuff with it.
}```

Same error.

Finally:

```for (let i = 0; i < 6; i  )
{
var temp = '{{data}}'
var value = temp[i]["key"]
//do some stuff with it.
}```

But that didnt work either. It started looping over the data character by character. (The output was 'undefined' 6 times.

However that didn't seem to work. Is there a way to get the 'i'th list of the 'data' list in JavaScript, or do I have to go back to my python file and send each dictionary trough flask one by one?

CodePudding user response:

Good day,

following along with your code example, it seems that you are attempting to read the contents of your list, manipulate each item and store the new value. In ECMA6 we have the map method for these kind of operations. The map method takes a function, that's to be performed on each element of the list. You will not have to declare i or loop over the list like you are doing in the old school way. Of course, there is a solution for that approach as well, but this is the modern way.

const data = [l1,l2,l3]

const newData = data.map( () => { return do_stome_stuff() }); //do some stuff

If you need to do something based on a key, you'll have to setup logic for this inside the function.

I hope this helps solving your problem!

  • Related