Swap out one JSON array with another while ensuring the original order is maintained

My API returns JSON data in the following format:

{'items':[
{'id': 1, 'quantity': 3},
{'id': 4, 'quantity': 7},
{'id': 5, 'quantity': 1}
]}

I have configured my page to fetch this API every 15 seconds. However, I have encountered a problem where the order of items in the array changes each time the API is called. This results in the blocks on my page changing their order as well. I attempted to address this issue by:

   for (var i in response.items) {
                   let current_item = response.items[i];
                   for (var i2 in original_items.items) {
                       if (original_items.items[i2].id === current_item.id) {
                           original_items.items[i2] = current_item;
                       }
                   }
               }

Unfortunately, this solution did not work as expected. Sorting the items by ID also proved to be ineffective. Any suggestions on how to tackle this issue?

Answer №1

Using ID for sorting is a reliable approach. After each response, including the initial one, simply arrange the objects in the array:

response.items.sort((a, b) => a.id - b.id);

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

Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out... Technologies Utilized: Vue (v3.0.0) Vue-Router (v4.0.0-0) Bootstrap (v5.1.1) The Objective: I have two pages (Home.vue, MetaUpdate.vue) and one component (Docum ...

Activate or deactivate Reactstrap tooltip depending on the button's current state

I've chosen to use Reactstrap (version 6.5.0) for the styling of my ReactJs project. Within my inline form, I have a submit button that remains disabled until the user has input all mandatory details. The goal here is twofold: Show the user a tool ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

Automate brush control and transmit pertinent data through coding

Extending on the query from yesterday's thread, I am working towards implementing multiple brushes. While my current brute force method is functional, I require additional functionality to programmatically manage each of these newly created brushes. ...

Tips for automatically closing one element when another is clicked

My goal is to create a menu that displays when I click on a link, and if another menu is already open, it should close before displaying the new one. Essentially, I want to achieve an accordion menu where only one menu is open at a time. However, despite m ...

Can someone please explain the result of console.log(error) and how can I convert it into a string?

Within a Node.js project that utilizes Typescript and is aimed at ES2020 compatibility, I have implemented a custom Error class in the following manner: class InvalidParamsError extends Error { } try { throw new InvalidParamsError(); } catch (error) { ...

The Boolean value retrieved from a NodeJS webservice behaves unexpectedly when incorporated into a test scenario

After calling a NodeJS webservice using the following code snippet: request({ url: "http://10.210.210.41:3001/trackable/lastPos", json: true }, function (error, response, body) { if (!error & ...

Cascading MVC 2 Dropdown menus

I am trying to bind a dropdown based on the change of another dropdown, but I keep getting an "Undefined" error. Here is my code snippet: <select id="BreakOutValue" class="input1_drop" onchange="onChange()" ></select> <%:Html.DropDownList( ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Encountering an issue with DateTimeField being undefined in a React.js application

I encountered an issue stating that DateTimeField is not defined while attempting to create a date picker in react + bootstrap. I referred to the following URLs for assistance: https://github.com/Eonasdan/bootstrap-datetimepicker Link to my code s ...

Losing a specific characteristic of data occurs when assigning a JavaScript object

After dedicating a full day to investigating this case, I found myself losing hope. const Tests = (state = INIT_STATE, action) => { switch (action.type) { case GET_TEST_DETAIL: return { ...state, test: {}, error ...

What strategies can I use to maintain the context while preserving the function's structure?

Is it possible to preserve the context and retrieve accurate data from an ajax response while following the current code structure? For instance: I am able to obtain the correct data in the second scenario. How can I achieve the same outcome within the e ...

Tips for utilizing components in slots in Cypress and Vue for effective component testing

Can someone help me figure out how to import a component into a slot using Cypress Component Testing with Vue? The documentation mentions the following for slots: import DefaultSlot from './DefaultSlot.vue' describe('<DefaultSlot />& ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Utilizing componentWillMount() with React Hooks: A step-by-step guide

According to the React official documentation, useEffect Hook can be compared to componentDidMount, componentDidUpdate, and componentWillUnmount combined for those familiar with React class lifecycle methods. If you’re familiar with React class lifecy ...

Using Mongoose to Implement the Repository Pattern in Node.js

As a newcomer to node.js with a background in .net, I am interested in applying some of the design patterns I used with c#.net. However, I am encountering challenges due to the differences in object-oriented nature between c# and JavaScript. Specifically, ...

Ways of assigning a null value to a key in a JSON body request

I am facing an issue with passing a null value to a key using a POST request in an API. I want to send JSON data where Exp and TeamID should be null, like below: { "ID":162617, "TextKey":"107737", "Exp":nul ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

The valueChanges event of a Reactive Form is activated whenever options from a datalist are selected

Whenever a user types into the input field, I am making an API call to retrieve and display data in a datalist for autocompletion (typeahead). control.get('city').valueChanges.pipe( map((searchText) => searchText.trim().toLowerCase()), fi ...

Adjust the message background color once it has been viewed

One of the buttons attached to a mat-menu has a red background when clicked. If you want to see it in action, check out this Stackblitz. .list-item.error { background-color:#FCE8FF; } However, if the button is clicked more than two times, the color sh ...