Creating a Vue.js data object with items arranged in descending order

While working with vue.js, I encountered an issue in sorting the items stored in my data object. Currently, they are sorted in ascending order and I need to display them in descending order instead. Below is a snippet of my vue template:

<div class="form-element form-element-checkbox" :key="key" v-for="(value, key) in items">
          <input
            :id="getID(value)"
            type="checkbox"
            :value="value"
            @change="updateFilter"
            v-model="selections"
            :checked="isSelected(value)">
          <label class="chk-small" :for="getID(value)">
            <span :aria-label="`Rated ${key}.0 out of 5`" class="star-rating noBlank" :style="{ width: `${key * 20}px` }"></span>
          </label>
        </div>

The current structure of the items object is as follows:

data() {
      return {
        items: {
          5: 'item_5',
          4: 'item_4',
          3: 'item_3'
        },
        selections: []
      };
    },

Even after attempting to utilize items.slice().reverse(), the desired ordering is not achieved. Any insights into what might be causing this discrepancy would be greatly appreciated.

Answer №1

If you find it difficult or unnecessary to convert your `items` dictionary into an array, you can simply utilize Object.keys() to extract its keys and manipulate them.

new Vue({
  el: '#app',
  data() {
    return {
      items: {
        // Note: even if you input them in descending order,
        // the JS engine will display them in ascending order.
        5: 'item_5',
        4: 'item_4',
        3: 'item_3',
      },
    };
  },
});
<script src="https://unpkg.com/vue@2"></script>

<div id="app">
  <p>itemsKeys: {{Object.keys(items)}}</p>
  <ol>
    <li v-for="(key, keyIndex) of Object.keys(items).reverse()">
      keyIndex: {{keyIndex}} / item key: {{key}} / item value: {{items[key]}}

    </li>
  </ol>
</div>

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

The server is unable to process the request for /path

After browsing various posts, I am still unable to identify the root cause of my issue. I am developing a donation page for an organization and need to verify if PayPal integration is functioning correctly. The error I am encountering lies between my form ...

How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this: <template> // content irrelevant </template> <script> export default { data() { return { redLocations: [ "Isfahaan", "Qom", ...

Using React to create an onScroll event listener within a mapped array

I am currently working on a setup where scrolling over an image mapped from an array updates the state with that image's coordinates, which in turn updates a Google Map. <CloudinaryContext cloudName="hcjmhcjf" fetchFormat="auto"> <div clas ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

Avoid the default behavior when employing jQuery for Ajax requests

I am facing an issue with preventing the default action when submitting a form using ajax. It seems that my code is causing a page refresh and clearing the form without sending any data to the database. I tried including the php processing script link in t ...

Guide to packaging TypeScript type declarations with an npm JavaScript library

I'm facing an issue with providing TypeScript type definitions for a JavaScript library. The library itself is written in TypeScript and transpiled by Babel, although this detail shouldn't affect the outcome. The problem lies in the fact that ne ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

Managing multiple updates or inserts in a MSSQL database using Sequelize

I have been tirelessly searching the online realms for a resolution over the past day but to no avail. The task at hand is performing a bulk upsert (update or insert) of a single model into a mssql database. Unfortunately, using bulkCreate with updateOnD ...

Issues with npm installation

Having trouble installing 'react-navigation' in my expo (react native) project using the command 'npm install --only=dev react-navigation'. I keep receiving warnings and am unsure how to proceed. See image link for details: enter image ...

Here is a unique rewrite:"Adjusting the prop of a Material UI Button component depending on screen size breakpoints can be achieved by utilizing

While using the Material UI Button component, I encountered an issue with conditionally determining the variant of the button based on screen size. Specifically, I want the variant to be 'outlined' on medium and larger screens, and no variant at ...

Tips for retaining input field content within a BootstrapVue table

Below is a BootstrapVue table I'm working with; https://i.sstatic.net/xu5Et.png The code, courtesy of this response, is showcased below; new Vue({ el: '#app', data() { return { filter: '', items: [ { i ...

Iterate over the object to verify if the field contains an empty array, then output null

Looking for help with handling empty arrays in an object: productDetails: { cislife: [], prime: [] } Is there a way to have null returned instead of an empty array if no values are available? For example, I'd like to determine if either t ...

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...

Display various formats in a pop-up window when different buttons are clicked

There has to be a simpler way to handle this situation. Currently, I have a modal with 4 hidden forms, one of which is active based on the "active" class. I want to show each form when different buttons like sign-up, forgot password, or sign-in are clicked ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

Custom shaped corrugated sheet in three dimensions

While constructing a house-like structure with corrugated sheets, I utilized BoxGeometry to outline the structure and adjusted vertices to create a corrugated sheet wall. I have been experimenting with creating a facade using corrugated sheets in the sh ...

The autocomplete feature in Google Maps is not functioning properly when used within a modal

I've integrated the Google Maps API to enable autocomplete address functionality for an input box on my page. However, I'm encountering an issue where everything works fine on the page itself, but it doesn't work when the input box is placed ...

Transferring the mistakes to the final return statement

I am currently working on a script that checks if a username is available or already taken. When the username is found to be taken, I need to assign an error message to my errors object. However, I am struggling with passing these errors from the inner if ...