Loop to populate Dropdown options from collection

Hi, I am trying to create a loop inside a wixQuery that populates the options in a dropdown input with values in cells from a datacollection. Here is my code;

let topicRef = $w(“#topicNumber”).text + “a”;
wixData.query(“GCSEF”)
.eq(“topicRef”, topicRef)
.find()
.then((results) => {
let item = (results.items[0]);
for ( let i = 1; i <= 3; i++) {
let opts = $w(“#taskMenu”).options;
let x = (i).toString();
opts.push({ label: (item.title +x) , value: x });
$w(“#taskMenu”).options = opts;
}
});

The aim is to add the values in cells “title1”, “title2” and “title3” for that topicRef.
I know that the query itself is working, it is the loop that is not.
It is returning “undefinded1”, “undefined2” and “undefined3” because I believe it is searching for the title column and then adding the value in the loop (+x), instead of searching for the title+x column.

Help!!

The problem is in this line:

opts.push({ label: (item.title +x) , value: x });  

you need to do instead:

opts.push({ label: (item[`title$x`]) , value: x }); 

Hi, that does not work either.
Can you please explain the logic of [title$x] ?

Thanks

It’s pure Javascript feature - Template literals (Template strings) - JavaScript | MDN

What exactly does not work? What do you get?
You can add some debugging logs (here is more info on how to do it - Velo: Testing and Troubleshooting Your Code | Help Center | Wix.com)
Add the line:

console.log(`Item: ${JSON.stringify(item)}`);

before you pushing the value to opts - and check the console in the preview mode. It will show the content of the whole item object you got.

Also please share (screenshot would be good enough) the GCSEF collection schema.


Above is the collection “GCSEF”.

Here is a copy of the log…


When testing this, the topicRef was set to 1a, and I am only testing in preview mode.

After clicking the button, the dropdown list creates three blank options underneath the options that were already present.

Oh, I see. Sorry, my bad - missed {} ! Try to use:

item[`title${x}`]

basically it’s same as item[“title” + x]

1 Like

Working now!
Thanks!

Yeah I thought there was a mistake there somewhere, but wasn’t sure how to resolve.

Thanks for your quick replies in resolving this issue : )

1 Like