Assign characteristics to the initial four elements in the array, then repeat the process starting with the fifth element, followed by the ninth element, and so on

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.

Answer №1

Generate an array containing different sizes. Iterate through the posts using the map method, and create a new object for each post by spreading the properties and including the corresponding size. Determine the size value based on the position of the post in relation to the array of sizes. Utilize promises or async/await when dealing with async fetch requests to populate the items instead of directly adding them.

const availableSizes = ['small', 'medium', 'large', 'extra-large'];

const items = await client.fetch(query).then(posts =>
  posts.map((post, index) => ({ 
    ...post,
    size: availableSizes[index % availableSizes.length] 
  }))  
);

Sample Scenario:

const fetchData = () => Promise.resolve([{ name: 'apple' }, { name: 'banana' }, { name: 'cherry' }, { name: 'date' }]);

const sizesList = ['small', 'medium', 'large', 'extra-large'];

const useCase = async () => {
  const items = await fetchData().then(posts =>
    posts.map((post, index) => ({ 
      ...post, 
      size: sizesList[index % sizesList.length] 
    }))  
  );
  
  console.log(items);
}

useCase();

Answer №2

it should function properly.

// assigning properties to the first 4 objects and then restarting on the 5th, 9th and so on.
  
  const postSize = ['s','m','l','xl'];
  
  for(let i = 0; i < posts.length; i++){
    for(let size of postSize){
      posts[i].size = postSize[size];
      i += 1;
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the name of this JavaScript function declaration syntax? (var) => {}

While perusing the most recent NodeJS documentation, I stumbled upon a novel approach to defining a function: fs.unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); Source: ht ...

Discover how to sum all the elements at a specific index within a JavaScript array using Vue.js

I am working on a project where I have created an array of products to display using VueJS. Each time a user selects a product, it is added to a list and the "Count" value increments. The "Total Price" for each product is calculated by multiplying the "C ...

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

JButtons are properly placed within a JPanel and should not be elsewhere

Greetings, I encountered a specific issue while trying to add a button to a panel using a for loop. The for loop is used in this scenario to create JButtons. nizButtona=new JButton[22]; for(int i=0;i<nizButtona.length;i++){ nizButtona[i] = new JB ...

Expression enclosed in double quotes within a JavaScript string

Our company has encountered an issue with an FTL that involves a link with JavaScript functionality. The problem arises when the value contains an apostrophe, causing the link to break. To address this, we utilized the js_string method to solve the issue. ...

How can you quickly track the AJAX requests being sent?

Is there a tool, preferably a Firefox extension, that can show me all AJAX subrequests? I want to be able to see the URL being requested and any GET or POST variables that are sent with it whenever an XMLHTTPRequest() is made. I haven't found anythin ...

Sending various Python variables to PHP

CSS Below is a simple form where users can input a URL: <form method="post" action="/" accept-charset="utf-8"> <input type="text" name="url" placeholder="Enter a URL" /> <button>Submit</button> </form> PHP (CodeIgn ...

Add the value to the array in MongoDb only if it does not already exist in

Looking to make updates to a nested array within a document only if the item is not already included in the array: await userCollection.findOneAndUpdate( { _id: ObjectId('616acc597ebda90ca6ffee21') }, { 'devices': { ...

The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

I'm grappling with a JavaScript issue and need some help. You can find the demo of the functioning script by the author right here. I've implemented the same code as displayed on his demo page. I've downloaded the worker.js file and ...

What is the maximum number of rows that Handsontable can handle at once?

Issue encountered in queued task: Security check failed - Too many TRs. Please specify table height to enable scrollbars. at WalkontableTable._doDraw (client/libs/handsontable-0.10.5/jquery.handsontable.full.js?37b46fd989b9a974c3501865b51effd7adec37e4:1285 ...

Creating a dynamic input box with an add/remove button in each row using jQuery

Need help with a jQuery-based UI that allows users to dynamically add input boxes. The desired look is as follows: Default appearance: INPUT_BOX [ADD_BUTTON] [REMOVE_BUTTON] Clicking on the [Add_Button] should add another row like this, and so on: ...

Rotating an array using the `memmove` function

If I have an array of integers like the following: #define MAX 5 int bar[MAX] = {0}; int foo[MAX] = {3,1,0,0,0}; My goal is to shift this array so that all empty entries are moved to the left, resulting in bar = {0,0,0,3,1}. I initially attempted to ach ...

The Axios response is coming back as a null value

//I utilized the context API to fetch data here const [allProfiles, setAllProfiles] = useState(""); const fetchAllProfiles = async () => { const res = await axios.get("http://localhost:5000/api/all-profiles"); setAllProfiles(res.data); }; ...

Struggling to understand how to utilize REF, Arrays, and Methods? Let me

Hey there, I'm currently working on a lab for my C# class that involves ref parameters, arrays, and methods. Unfortunately, I've run into a few problems and am in need of some assistance. To simplify things, I've broken down the issues I&apo ...

Incorporating a class into ever-changing Bootstrap Table rows

Looking to enhance my table rows with a class, excluding the header. Struggling to find a way to do this. Any ideas? This is the table in question: <table id="table" class="hidden table table-bordered table-striped table-hover"> <thead> ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

Walls that collide in three.js

I am currently developing a game using three.js and despite being new to this field, I have extensively studied collision documentation. To handle collisions between my boat (inside a cube) and the islands (contained in cubes), I implemented raycasting. He ...

What are the memory-saving benefits of using the .clone() method in Three.js?

As I work on my game project, I am including a whopping 100,000 trees, each represented as a merged geometry. Utilizing the tree.clone() method to add them from a cloned model has helped save a significant amount of memory. Unfortunately, the game's p ...

Utilize a PHP variable in a JavaScript file through Ajax for seamless functionality

In my PHP script, I retrieve the content of a query from a Postgresql database : <?php require_once 'connection.php'; $query1 = pg_query("This_is_my_query"); $instruction = "["; while ($row = pg_fetch_array($query1)) { ...

Redirect events in Backbone views

Is there a way to navigate to a different page when a specific event is triggered in a View using Backbone? events: { 'click .btn': 'signin' }, render: function() { tmp = this.template(); this.$el.html(tmp); }, signin: func ...