I am attempting to filter a collection then create a variable that would contain an array of all items from a specific field from the filtered dataset. In the code below, the variable field2 is undefined. Any suggestions?
import wixData from ‘wix-data’;
$w.onReady( function () {
$w(“#dataset1”).onReady( () => {
$w(“#dataset1”).getItems(0, 10000)
.then( (result) => { let items = result.items;
console.log(items); let field2=items.field2;
console.log(field2);
});
});
The getItems() function does just that, it returns items (plural). So, you will need to get each item, and from that individual item you can then retrieve the desired field. Something like this:
let items = result.items;
console.log(items);
let item = items[0];
let field2 = item.field2;
console.log(field2);
Also, you should be aware that the default limit on the number of returned items is 50. The maximum allowed is 1000. See the limit() API for more information.
So it looks like the getItems may not work for what I am trying to do.
This is my problem: I am trying to query a filtered dataset. Of course, query can only be used on a collection, so I am trying to tell the query to all retrieve items that were previously filtered in my dataset1. So I tried the solution below. Is there a better, cleaner solution to this? Thanks!
Your query won’t work since filteredItems contains an array of items (as objects). If you want to see if the random collection contains certain fields, you will have to retrieve those fields from the array of filteredItems.
Also, your getItems() still will not work since you are trying to retrieve more than the limit allows.
You could either use the Javascript filter() function on the returned array of items, or set a new filter on the dataset using setFilter() .
To clarify, I need to query the collection in order to update field values in the collection - but only for those items that exist in the filtered dataset1. My query function continues as follows…
You can use getItems() to get the filtered results of the dataset. Then loop through the array of filtered results, and for each item, so something like this: