The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separator, for instance. This is within a Vue (.ts) environment.

<div v-for="(count, category) in products[product]" :key="category">
   <div>{{ category }}</div>
   <div>{{ Number(count).toLocaleString() }}</div>
</div>
const products = {
  "shoes": {
    "shoes4men": 1402,
    "shoes4women": 99,
    "shoes4kids": 3000,
    "shoes4athletes": 57
    }

Answer №1

If we consider the scenario where "category" is a string because it acts as the key in a dictionary.

Let's think of this as "value and key" instead of "count and category":

<div v-for="(value, key) in products[product]">

To facilitate sorting, you can first convert to an array, sort it, and then use it with v-for:

<div v-for="(product) in Object.keys(products).sort()" :key="product">
    <div v-for="(category) in Object.keys(products[product]).sort()" :key="category">
        <div>{{ category }}</div>
        <div>{{ Number(products[product][category]).toLocaleString() }}</div>
    </div>
</div>

For more information, visit: https://vuejs.org/guide/essentials/list.html#v-for-with-an-object

Note: Avoid performing computations like sorting directly in the template as they can be costly, as pointed out by Estus Flask.

If you don't need direct access to the category with syntax like:

Products["shoes"]

You can organize data in a sorted manner using a different structure, for example:

const products: Category[] = [
    {
        "name": "shoes",
        "categories": [
             { "name": "shoes4athletes", "value": 57 },
             { "name": "shoes4kids", "value": 3000 },
             { "name": "shoes4men", "value": 1402 },
             { "name": "shoes4women", "value": 99 }
        ]
    }
]


<div v-for="(product) in products" :key="product.name">
    <div v-for="(category) in product.categories" :key="category.name">
        <div>{{ category.name }}</div>
        <div>{{ Number(category.value).toLocaleString() }}</div>
    </div>
</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

How can we pass an optional boolean prop in Vue 3?

Currently, I am in the process of developing an application using Vue 3 and TypeScript 4.4, bundled with Vite 2. Within my project, there exists a file named LoginPage.vue containing the following code: <script lang="ts" setup> const props ...

Trouble with browser caching when utilizing code-splitting for production? (Encountering difficulties fetching dynamically imported module)

Using Vue + Vite for my web application, I have implemented code-splitting in the router file for most routes. An example of this is: { path: "settings", name: "settings", component: () => import("../views/SettingsView.vue&q ...

Developing web applications using a combination of PHP, MySQL, and

I am in need of creating an HTML form that functions as CRUD. This form should be able to record inputs such as "row_number", "channel_name", and "ip_address". It will store all the data in a MySQL table using the "ORDER BY row_number" function. The form i ...

I am having trouble installing the latest version of Bun on my Windows operating system

When attempting to install Bun on my Windows laptop using the command npm install -g bun, I encountered an error in my terminal. The error message indicated that the platform was unsupported and specified the required operating systems as darwin or linux w ...

Understanding ReactJS's process of batching all DOM updates within a single event loop, ultimately minimizing the number of repaints needed

While perusing an article on DOM updates in ReactJS, I came across the concept of React updating all changes within a single event loop. Having a background in understanding event loops in JavaScript and how they function in core JavaScript, I am curious ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

Slide in parts gradually by scrolling up and down, avoiding sudden appearance all at once

I have implemented a slider on my website using jQuery functions. For scrolling down, the following code snippet is used: jQuery("#downClick").click(function() { jQuery("html, body").animate({ scrollTop: jQuery(document).height() }, "slow"); ...

Having trouble with triggers: Unable to locate the module 'csv-parse/sync' for parsing

Currently, I am utilizing Firebase functions to create an API that is capable of parsing CSV files. However, whenever I attempt to utilize csv-parse/sync instead of csv-parse, my deployment to Firebase Functions encounters a failure with the subsequent er ...

Exploring the process of extracting a nested JSON value using Postman

I am currently facing an issue with parsing the json response from a post request, and then sending the parsed data to a put request. Here is the response body: { "createdBy": "student", "createdOn": "2019-06-18", "Id1": "0e8b9 ...

Encountering an issue where attempting to map through a property generated by the getStaticProps function results in a "cannot read properties

Greetings, I am fairly new to the world of Next.js and React, so kindly bear with me as I share my query. I have written some code within the getStaticProps function in Next.js to fetch data from an API and return it. The data seems to be processed correct ...

When the bounds are adjusted, removing markers in Vue Cookbook's Google Map

I've encountered an issue with clearing markers after updating new bounds on a map. Whenever I post a request with new bounds, new markers get added to the map while the old ones remain in place. This situation becomes quite awkward for me because the ...

Combining dynamic classes within a v-for loop

Here's my custom for loop: <div v-for="document in documents"> <span></span> <span><a href="javascript:void(0)" @click="displayChildDocs(document.id)" :title="document.type"><i class="fas fa-{{ d ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Fetching server-side data for isomorphic React app: A guide to accessing cookies

Currently, I am in the process of developing an isomorphic/universal React + Redux + Express application. The method I use for server-side data fetching is quite standard: I identify the routes that match the URL, call the appropriate data-fetching functio ...

What is the best way to ensure that two Node processes do not insert duplicate database records when running concurrently?

My Lambda function receives a high volume of events simultaneously, causing AWS to spin up multiple instances to handle the load. The function written in Node.js uses Knex to interact with a Postgres database, checking if a record with a specific ID exists ...

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

Utilizing web components from NPM packages in conjunction with Svelte

My current project involves the development of a simple Single Page App (SPA) using Svelte. I have successfully implemented a basic layout and styling, as well as an asynchronous web request triggered by a button click. Now, my next objective is to utiliz ...

`Is there a way to maintain my AWS Amplify login credentials while executing Cypress tests?`

At the moment, I am using a beforeEach() function to log Cypress in before each test. However, this setup is causing some delays. Is there a way for me to keep the user logged in between tests? My main objective is to navigate through all the pages as the ...

The node.js oauth-1.0a implementation is successful in authenticating with Twitter API v1.1, however, it encounters issues

Having come across this function for generating an oauth-1.0a header: // auth.js const crypto = require("crypto"); const OAuth1a = require("oauth-1.0a"); function auth(request) { const oauth = new OAuth1a({ consumer: { key ...

Vue 3: Leveraging Functions Within Mutations.js in Vuex Store to Enhance Functionality

In my mutations.js file, I have encountered a situation where one function is calling another function within the same file. Here's an example of my code: export default { async addQuestionAnswer(state, payload) { alert(payload); this.update ...