I've been working on a project using sanity.io. I retrieve data, store it in an array, and then send it to my front-end using express and ejs.
Each post
stored in the array will be represented as a card. These cards will have different css classes to display them as small, medium, large, or extra-large.
My objective is to iterate through the array and add a property to each object that can be accessed on the front end to determine the size of the card.
Although the following example illustrates what I aim for, this hardcoded approach won't work when new posts are added via sanity.io:
// desired result
posts[0].size = 's'
posts[1].size = 'm'
posts[2].size = 'l'
posts[3].size = 'xl'
posts[4].size = 's'
posts[5].size = 'm'
posts[6].size = 'l'
posts[7].size = 'xl'
I believe that I need to iterate through the array, assign properties to the first 4 objects, then repeat the process for the next 4 objects, and so on.
let items = [];
// Retrieve and add to array
client.fetch(query).then((posts) => {
posts.forEach((post) => {
items.push(post);
});
// Assign properties to first 4 objects, restart sequence at 5th, 9th, etc.
for(let i = 0; i < posts.length; i+=4){
posts[i].size = 's'
posts[i+1].size = 'm'
posts[i+2].size = 'l'
posts[i+3].size = 'xl'
}
});
The code snippet above is incorrect, but it reflects my current progress. Any assistance or guidance on this would be greatly appreciated.