Order the array according to the attribute of the intermediate model

My application involves three models on the frontend (using Vue/Vuex-ORM): Category, CategoryItem, and Item.

I have successfully fetched an array of categories, each containing an array of items. The relationships between these models are defined in an intermediate join model, allowing me to access them like this:

// array of categories with nested items
const categories = Category.query().where('pack_id', this.selectedPack.id).with('items').get();

categories.map(category => {
    category.items.forEach(item => {
        console.log('item.pivot: ', item.pivot); // accessing join model
        // how can I order items based on item.pivot?
    })
})

As I iterate through each category's items with .forEach, I want to sort them based on item.pivot.position.

Initially, I attempted to create a new empty array inside the .map function and then push values based on position comparison. However, I struggled to implement this logic effectively.

Any suggestions or guidance would be greatly appreciated!

Answer №1

After posting my question, it only took me half an hour to solve the issue myself! For anyone interested, here is what I did:

retrieveCategories() {
    const categories = Category.query().where('pack_id', this.selectedPack.id).with('items').get();

    categories.forEach(category => category.items.sort(this.compare));
    return categories;
}

compareItems(a, b) {
    let comparison = 0;
    if (a.pivot.position > b.pivot.position) comparison = 1;
    else if (a.pivot.position < b.pivot.position) comparison = -1;
    return comparison;
},

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

Adjusting the scope value directly within a directive

I have a validation message that starts off hidden when the page loads due to the ng-show attribute. When the user clicks to delete an entry, the confirmation message for successful deletion appears by changing the ng-show value to false. Now, I need to h ...

Best practices for Django project implementation using only pure JavaScript, HTML, and template tags

As a newcomer to website development, my decision to use Django was influenced by my familiarity with Python and the complexity of the project at hand. I am seeking advice on the best practices for creating templates using the Django framework. My query i ...

Can a cancel button be added to a mobile keyboard for easier use?

Looking to streamline the mobile UI for my Vue-built SPA by removing unnecessary buttons. Encountering an issue with form submission on mobile keyboards triggering unwanted listeners. Is there a way to introduce a cancel button for forms on mobile? ...

What's preventing the `@change` trigger from functioning properly with v-data-picker?

In my Vue.js application, I am utilizing the v-calendar package. I am trying to pass selected date range values to the parent component. However, why is the @change trigger not working? Parent.vue: <template> <div> <Child @set ...

Having trouble getting Bootstrap-select to function properly with dynamically populated options in Vuejs?

I encountered an issue while trying to implement bootstrap-select in my project. Initially, the pre-created select option functioned correctly. However, when the options of the select were dynamically generated, the plugin failed to work without any visibl ...

The Three JS library seems to be malfunctioning as it is only displaying a blank, black screen with no

After browsing through similar questions on various sites, I have attempted all the recommended suggestions. From adjusting camera positioning to calling the render function and setting ambient light, I've tried everything mentioned in forums but noth ...

Modifications made in ajax success do not appear on the page without a manual refresh

I have a JavaScript AJAX block that performs some operations and then updates a text box on my webpage. $.ajax({ type: "POST", url: "/update_page/", data: JSON.stringify({'itemId': parseInt(item_id)}), cache: false, success: ...

a JSON object containing an empty array

Here is the JSON data that I am dealing with: { "users": [{ "user": { "user_id" :"a11uhk22hsd3jbskj", "username" :"tom", "location" : null ...

Create a live notification feature for an HTML5 Django web application to keep users updated in real-time

Currently, I am developing an HTML5 web application using Django and Apache. The main objective of the app is to monitor multiple devices. All client-side logic is written in Angular, while data is fetched from JSON-based REST calls to the backend. Everyt ...

Is there a way to extract a string from a file saved on my device?

Is there a way to read files using JavaScript by specifying the "file path" without having to manually click an input button every time? I've tried using jQuery to cheat it, but it seems like jQuery can't modify the input value. Any other sugges ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

The functionality of JavaScript in jQuery mobile seems to require a manual refresh to work properly

Recently, I encountered an issue with my jQuery mobile page that contains JavaScript. The trouble is that the JavaScript doesn't function properly until the page is refreshed. Below is the snippet of code causing the problem: jQuery(function($) { ...

Having the same name for multiple query parameters does not result in an array being returned

Using the link http://example.com/users?test=1&test=2 router.route('/users/?').get((req, res) => { console.dir(req.query) //=> { test : 1 } }) The output is { test : 1 } instead of an expected array [ 1, 2 ]. Even ?test[]=1&test ...

The functionality of jQuery is operational on jsFiddle, however it appears to not be functioning properly

THE CHALLENGE This is an intriguing issue that seems to have a straightforward solution. Thanks to the assistance of @jessegavin, I incorporated a jQuery function into my webpage to manage the playback of HTML5 audio elements. The code runs smoothly on a ...

What could be causing the position method to not provide the anticipated results?

Why is the position method not returning [left: 100, top: 10] in this particular scenario? <!DOCTYPE HTML> <html> <head> <style> #parent1 { width: 300px; height: 200px; border: solid 9px pink; } #child1 { position: ...

Dealing with a mysterious Vuejs object that remains undefined within a watched property

Encountering an issue with Vue.js's watched property. Despite the list being defined, I am receiving the error: Cannot read property 'list' of undefined. This occurs after the if check at the line var index ..... watch: { selectedRole: () ...

Extracting information from this array using JavaScript

After struggling for a day, I finally managed to get some output from PHP instead of just the word "array". What a relief! (check out this link for the solution) Basically, this is the data returned from an XMLHTTP request to PHP, handled through a JS ca ...

Applying Vuelidate to a v-model containing an array is a great way to

I have implemented vuelidate for select options to make them required. It's working fine when the v-model has a single name like $v.selectedWorkflow.$model <div class="form-group" :class="{ 'form-group--error': $v.selectedW ...

What is the process for modifying the headers of a post request in Express when

I have a Node/Express application and I'm looking to incorporate an image upload feature into an order form. While I can successfully use the action link in the HTML form to perform a POST request, I also want my JavaScript file associated with this ...

What is the best way to limit an input field to only allow up to two decimal places and a maximum of 10 total

Is there a way to limit an input field to only accept two decimal places and have a maximum of 10 digits? I have implemented a function that is triggered by the onkeypress event and checks the length of the value entered into the input field. I have manag ...