Vue.js: Iterating over objects using v-for causes keys to be displayed in unexpected order

I've encountered an issue where Vue is not honoring the sequence of keys. The initial data I provide to the Vue component as a prop appears as follows:

[
  { id: 1, event_name: "event 1", scheduled_at: "2021-01-01" },
  { id: 2, event_name: "event 2", scheduled_at: "2021-01-01" },
  { id: 3, event_name: "event 3", scheduled_at: "2021-01-05" },
  { id: 4, event_name: "event 4", scheduled_at: "2021-01-05" },
  { id: 5, event_name: "event 5", scheduled_at: "2021-01-02" }
]

Subsequently, I have a calculated prop called groupedEvents that organizes the events by date (using lodash's groupBy function). Here is the resulting output:

{
  2021-01-01: [
    { id: 1, event_name: "event 1", scheduled_at: "2021-01-01" },
    { id: 2, event_name: "event 2", scheduled_at: "2021-01-01" },
  ],
  2021-01-02: [
    { id: 5, event_name: "event 5", scheduled_at: "2021-01-02" }
  ],
  2021-01-05: [
    { id: 3, event_name: "event 3", scheduled_at: "2021-01-05" },
    { id: 4, event_name: "event 4", scheduled_at: "2021-01-05" },
  ]
}

The main issue lies in the fact that when I utilize a v-for loop on groupedEvents, the order of groups gets jumbled or overlooked.

<div v-for="(group, key) in groupedEvents">{{ key }}</div>

The displayed result is:

2021-01-01
2021-01-05
2021-01-02

instead of the desired:

2021-01-01
2021-01-02
2021-01-05

Additional note: ordering function utilized:

let grouped = _.groupBy(this.events, (event) => { return event.scheduled_at })

Answer №1

To loop through the sorted keys of the groupedEvents, you can utilize a different computed property and implement your own sorting method:

const childcomponent = Vue.component('childcomponent', {
  template: '#childcomponent',
  props: ['events'],
  computed: {
    groupedEvents() {
      return _.groupBy(this.events, 'scheduled_at');
    }
  }
});

new Vue({
  el:"#app",
  components: { childcomponent },
  data: () => ({
    events: [
      {id: 1, event_name: "event 1", scheduled_at: "2021-01-01"},
      {id: 2, event_name: "event 2", scheduled_at: "2021-01-01"},
      {id: 3, event_name: "event 3", scheduled_at: "2021-01-05"},
      {id: 4, event_name: "event 4", scheduled_at: "2021-01-05"},
      {id: 5, event_name: "event 5", scheduled_at: "2021-01-02"}
    ]
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

<template id="childcomponent">
  <ul>
    <li v-for="key in Object.keys(groupedEvents).sort()">
      {{ key }}: {{ groupedEvents[key] }}
    </li>
  </ul>
</template>

<div id="app"><childcomponent :events="events"/></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

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example: $scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }]; $scope.create = function(task) { tmp.tags = angular.toJson( ...

Struggling with collaborating with an assistant in handlebars and express operations

When attempting to utilize helpers, an error arises: ReferenceError: a is not defined The goal is to display home.hbs located under the views directory. The file contains: <li class="{{#if_eq title "Home"}}active{{/if_eq}}"> <a href="/">H ...

"Transforming the CSS attribute from 'none' to 'block' for a

Within my project, I have implemented ajax to retrieve html content for the cenDiv div. This is how my ajax code looks: $.ajax({ dataType: 'html', type: "POST", url: "oat.php", data: { standby: standby }, success: function(data) ...

Improving file reading and parsing efficiency with fast random access using csv-parse in Node.js

I recently encountered a challenge while working with the csv-parser library in node for parsing large CSV files. The files I work with can range from 50,000 to 500,000 lines or even larger. My task involved performing computations on this data and then su ...

Utilize Jquery to transform 3 arrays into separate objects distinguished by unique IDs

Recently, I've been experimenting with a very simplistic jquery admin area menu. My goal is to have jQuery create 3 identical menus with different IDs. I was able to accomplish this by creating a function and calling it three times with various variab ...

Are SVGs with JavaScript for parallax effects?

Recently, I stumbled upon a webpage that left me in awe (Link Below). It seems to combine parallax effects with dynamic information that appears on screen as the user interacts with different elements. Despite my attempts to find more information about thi ...

I am struggling to display an array of objects retrieved from the server in the UI using AngularJS

I am receiving an array of objects as a JSON from the server. When I try to access my service URI from HTML, I encounter the following array in my console: "angular.js:13920 Error: [$resource:badcfg] http://errors.angularjs.org/1.5.8/$resource/badcfg?p0= ...

IE8 and IE9 encountering "Access is denied" error due to XML causing XDomainRequest (CORS) issue

Sorry if this seems repetitive, but I am unable to find a definitive answer to similar questions. Whenever I attempt to make a CORS request for XML, I consistently encounter an "Access is denied" JavaScript error in IE8. The code I am using is based on t ...

What is the best way to combine a string with a variable in sass?

Is there a way to merge a string and a variable in Sass to form a variable name that is already present? $size: "sm"; $button-sm: 1rem; $buttom-md: 1.5rem; body { font-size: $button-#{$size}; } The desired output is: body { font-size: 1r ...

The express post request is unable to locate the body and its contents

Check out my JavaScript code snippet below: const handleClick = () => { const fd = new FormData(); fd.append("desc", value); fetch("http://localhost:5000/notes/create", { method: "POST", body: fd, ...

Issue with utilizing Vuejs variable in Google Maps Matrix API function

Having trouble accessing a Vue.js variable in a function using the Google Maps Matrix API. I am trying to use the Google Distance Matrix API to calculate the distance between two locations. I have declared a variable globally and changed it within a functi ...

two adjacent elements filling the entire height of the window at 100% dimensions

Is there a way to place two elements side by side, with one of them (the textarea) always being 100% height of the window? I've looked at similar questions here but can't figure out how to make it work. Can you help me with this? html: <div ...

Understanding the explanation of the function declaration

declare abstract class CustomBootstrapConsole<X extends AppContext, Y extends Options = DefaultOptions> { protected customService: CustomConsoleService; protected customContainer: X; protected readonly customOptions: Y; constructor(op ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

Unable to submit POST request in Node.js

Seeking assistance to resolve a persistent error that has been causing me trouble for quite some time. This issue is preventing me from adding data to my database successfully. Any help or guidance on this matter would be greatly appreciated. This sectio ...

Tips on validating emails using mongoose

As a beginner with Mongoose, I have a code snippet here. How can I validate the text that appears after the @ symbol in an email before saving it to the database? var user = new User ({ firstName: String, lastName: String, email: String, ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...