What is the best way to iterate through an object of objects in Vue.js using mapping?

I am looking to develop a function that maps different items to specific color thresholds. Here is an example of what I have in mind:

export const mapMetricsToValue: any = {
    item1: {
        0: 'green--text',
        0.3: 'red--text',
        0.45: 'orange--text',
    },
    item2:{
        0: 'yellow--text',
        0.5: 'blue--text',
        0.65: 'purple--text',
    }
};

export function getTextClass(metric: string, value: Number): string {
    return mapMetricsToValue(metric,value);
}

The concept here is to have different items (like item1, item2, etc.) each with their own thresholds for color assignment. For instance, for item1:

-if (0<item1<0.3) it should return green, 
-if(0.3<item1<0.45) it should return red,
-else it should return orange

Similarly, item2 would have a different set of thresholds and colors. The goal is to have a function (getTextClass) that returns the appropriate color based on the item and its threshold.

I would appreciate any assistance with this. Thank you!

Answer №1

My recommendation would be to always follow a structured approach and define interfaces for better organization. I suggest abstracting Metric and its container into interfaces as shown below:

export interface Metric {
    lowerBound: number;
    color: string;
}
export interface MetricItem {
    name: string;
    metrics: Metric[];
}

This approach allows for easier reference to specific values by name when needed in the future. To implement this, we can create a mapMetricsToValue array like this:

export const mapMetricsToValue: MetricItem[] = [
    {
        name: 'item1',
        metrics: [
            {
                lowerBound: 0,
                color: 'green'
            },
            {
                lowerBound: 0.3,
                color: 'red'
            }, //...
        ]
    },
    {
        name: 'item2',
        metrics: [
            {
                lowerBound: 0,
                color: 'yellow'
            } //...
        ]
    }
];

Mapping a color to a specific value is then easily achieved by iterating over the array of values for a given MetricItem and checking if the value falls within the specified range defined by the lowerBound values. It is important to ensure that the values are sorted by lowerBound in ascending order for this method to work correctly, but sorting can be done using another function if needed.

export function getTextClass(metric: MetricItem, value: number) : string {
    let metrics = metric.metrics;
    let len = metrics.length;

    for(let i = 0; i < len; i++) {
        let currentMetric = metrics[i];

        if(i === len - 1) {
            return currentMetric.color;
        }

        let nextMetric = metrics[i + 1];

        if(currentMetric.lowerBound <= value && nextMetric.lowerBound > value) {
            return currentMetric.color;
        }
    }
}

To retrieve a specific metric based on its name, the following function can be used:

export function findMetricByName(name: string, metrics: MetricItem[]): MetricItem {
    return metrics.find(metric => metric.name === name);
}

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 JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...

The combination of Sequelize and TypeScript does not support the usage of the .create method with type attributes

The IDBAttribute - interface IDBAtribute { readonly id: number; readonly createdAt: Date; readonly updatedAt: Date; } User attributes defined as IDBMoviesAttributes - interface IDBMoviesAttributes extends IDBAttribute { readonly title: str ...

Having trouble getting Vue create to work? If you're not seeing any output in the console or Vue UI,

I'm having trouble getting the Vue CLI to work. When I tried using vue create hello-world, it didn't return any output. I also attempted using vue ui, which showed ...

NextJS is currently unable to identify and interpret TypeScript files

I am looking to build my website using TypeScript instead of JavaScript. I followed the NextJS official guide for installing TS from scratch, but when I execute npm run dev, a 404 Error page greets me. Okay, below is my tsconfig.json: { "compilerOption ...

What is the method for specifying a string argument type from a string list and executing a mongo db query?

Is there a way to specify the argument type in a function as a string from a list of strings in order to run a MongoDB query? Here is what I am currently attempting: users.services.ts async findOne(key: "_id" | "email" | "username", value: string) { ...

Stop the container from growing in height due to column expansion

I'm facing an issue with my Vuetify two-column layout. The left column contains media with varying aspect ratios, while the right column houses a playlist. As the playlist grows in length, it extends the container, leaving empty space below the media. ...

Delivering static files with NGINX and Vue.js

I've set up a basic node server to serve a Vue.js application that I built. The server is currently running on localhost:3000 Nginx is configured to listen on port 80 The application has been deployed on the local IP address. Nginx Configuration: ...

Having trouble clicking a button using Python and Selenium that triggers the `openWindow` function

I am attempting to interact with a button using Python Selenium WebDriver (Chrome). Here is the HTML code of the button: <button type="button" class="button blue" onclick="openWindow(LINK_HERE, 'idpage6')">Like</button> (I had to re ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

Using Axios.put will only modify specific fields, not all of them

Recently, I came across a tutorial that utilized nodejs, mysql2, express, and vuejs. The tutorial can be found at: For my project, I decided to use my custom database and tables instead. However, I encountered an issue when sending an axios.put request - ...

Add array as an element within another array

After initializing the data, I have an object structured like this and I am able to push data using the method below: myObj = { 1: ["a", "b", "c"], 2: ["c", "d", "e"], } data: { types: {} }, methods: { pushValue(key, value) { var ...

When attempting to set a JSON array in state, the resulting JavaScript object does not display correctly

As part of my experimentation with fetch APIs in react, I have set up a server that provides dummy data. In the componentDidMount lifecycle hook of my component, I am making a fetch call to retrieve the data. componentDidMount(){ axios.get('http:// ...

Navigate to the anchor element within the webpage that contains adaptive images

My Bootstrap 4 page contains responsive images and anchor tags within the text. .img-fluid { max-width: 100%; height: auto; } Once I navigate to this page by clicking a link (e.g., 'mypage#section-one'), the page initially loads on the ...

Prevent the page from refreshing when a value is entered

I currently have a table embedded within an HTML form that serves multiple purposes. The first column in the table displays data retrieved from a web server, while the second column allows for modifying the values before submitting them back to the server. ...

Function execution in React component is not happening

Trying to master React and next.js with Firebase as the database has been an interesting journey. I recently encountered an issue where a function in my component is not being called. Upon trying to debug using console.logs(), it appears that the function ...

How can I use jQuery to display a div alongside the element that is currently being hovered over?

Imagine having multiple divs similar to these: UPDATE: <div class="ProfilePic"> <a href="#"> <img src="lib/css/img/profile_pic1.png" alt="" class="ProfilePicImg"/> </a> <div class="PopupBox" style="display: ...

Troubleshooting issues with Angular 2 HTTP post and Web API integration

Here is an example of my Web Api Core Controller Method: public void Post(Sample sample) { _sampleService.CreateSample(sample); } The Sample POCO is defined as follows: public class Sample : BaseEntity { public string BarCode { get; s ...

Issue with Retrieving a particular table from SQL Server using mssql in javascript ('dbo.index')

I am currently experiencing an issue with trying to access a table named dbo.Index from SQL Server in my node js express application. Unfortunately, whenever I attempt to do so, the operation fails and returns no data. Below is the code snippet in questio ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...

Get started with the free plan for sails.js on Paas

Looking to test out my sails.js application deployment options. Can't seem to find sails.js on the supported list for Heroku and OpenShift's node.js offerings. Are there any free Platform as a Service (PaaS) plans available for sails.js? ...