The filter function results in a blank array being returned

I'm facing a dilemma, I have a constant defined as

export const STATUS = [{
  0: 'Draft',
  1: 'Sent',
  2: 'Processing',
  9: 'Processed',
  3: 'Scheduled',
  4: 'Filed',
  5: 'Suspended',
  6: 'Protocol Error',
  7: 'Processing Error',
  8: 'Reading Error',
}];

and I've been trying to retrieve the values using this method

public constantFormatter(params) {
    const status = STATUS.filter((p) => p === params.value);
}

but it keeps returning empty, and I can't figure out why. Has anyone else encountered this issue?

Answer №1

If you're looking to define a set of constants, an enum is the way to go:

export enum STATUS {
  Draft,
  Sent,
  Processing,
  Processed = 9, // Only these two are needed since enums auto-increment and this one was out of order
  Scheduled = 3,
  FiledAway,
  Suspended,
  "Protocol Error",
  "Processing Error",
  "Reading Error",
};

export function constantFormatter(params: {
  value: number
}): string {
  return STATUS[params.value];
}

Answer №2

You have encountered an error while trying to retrieve a property called 'params' that does not exist.

The issue stems from having an array consisting of only one object, which lacks the specified 'params' property. To access an object using a variable value, you must use array notation (object[whatever]) instead of dot notation (object.whatever).

Consider the following example:

const STATUS = [{
  0: 'Draft',
  1: 'Sent',
  2: 'Processing',
  9: 'Processed',
  3: 'Scheduled',
  4: 'Filed',
  5: 'Suspended',
  6: 'Protocol Error',
  7: 'Processing Error',
  8: 'Read Error'
}];

function constantFormatter(params) {
    return STATUS[0][params];
}

console.log(constantFormatter(4));

Answer №3

If you are unable to modify the original array, one way to access object values from it is by utilizing the Object.values() method.

const STATUSES = [{
  0: 'Draft',
  1: 'Submitted',
  2: 'Processing',
  9: 'Processed',
  3: 'Scheduled',
  4: 'Filed',
  5: 'Suspended',
  6: 'Protocol Error',
  7: 'Processing Error',
  8: 'Reading Error'
}];

console.log(Object.values(STATUSES[0]));

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

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...

Efficiently updating arrays within object arrays using MongoDB

I have the following data structure: { data: [ {pos:"0", moreData: ["a", "b"] }, {pos:"1", moreData: ["a", "c"] }, ]} I want to update this structure by adding a letter to moreData where pos ...

The synchronization issue between ng-class and animation

I'm experiencing a strange issue with ng-class and suspect that it may be related to a race condition. Here is the example on Plunker: example Below is the relevant JavaScript code: self.slideLeft = function() { if (self.end_index < se ...

Can TypeORM create an entity for a many-to-many relationship that functions like ActiveRecord's join table concept?

Consider a scenario where there is a Guardian entity connected to a Student entity. The goal is to establish their many-to-many relationship in TypeORM by introducing a new entity called StudentGuardianRelationship. This intermediary entity serves the purp ...

Error encountered with CORS in a Socket.io Express HTTP server backend

While developing an app that utilizes express for the backend, I decided to incorporate socket.io for real-time chat functionality. Everything was working flawlessly on postman until my front end react code triggered a cors error when making a GET request ...

Utilizing HTML5 to target and conceal an entire column dynamically with the help of JavaScript/jQuery

If I need to hide an entire column (consisting of one TH and multiple TDs) using HTML5, what is the best approach? In the past, I would use a "Name" attribute to identify all the columns I wanted to hide at once by iterating over document.GetElementsByNam ...

What is the best way to create two fields side by side within a single row?

I'm struggling to merge the data array of two different identity types into one row as a field. Here's the code I've written: import React from 'react' import {Form,Field,ErrorMessage,Formik} from 'formik' import * as yup ...

Utilizing JQuery to populate DIVs with JSON information

Hey! I recently received some helpful advice from a coding expert, and now I'm in the process of restructuring my code based on these recommendations: When using $.each(), you have the option to return true or false. If you return false, the loop wi ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

Error: vue is not defined and cannot read property '$bvModal'

It seems like this isn't scoped properly within my function. When attempting to call this.$bvModal.show("signinModal") in order to display the modal, I encounter the following error: Uncaught TypeError: Cannot read property '$bvModal' of u ...

Unable to use innerHTML function on Blogger platform

I am currently working on a basic voting system. It functions perfectly when the two files are in the same location (locally). However, once I publish it on my blogger platform, the system fails to display the results. (When a user clicks to vote, it regi ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

Problem with adding card to customer in Stripe using Angular 2 and Express

I encountered an issue while attempting to add a card to a customer. My Express server, which handles the post request to Stripe, successfully registers a new customer but fails to include credit card information for the new customer. Within my Angular 2 ...

What is the best way to attach an onClick event to a PHP-generated link?

Currently, I'm attempting to implement an onclick event on a link within a PHP file. $body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . ...

How come process.env.username is pulling the computer hostname (in Windows 10), rather than the key-value pair specified in the config.env file?

In my config.env file, I set up username and password variables and attempted to retrieve them using the dotenv package. However, when I try to access the username variable, it returns the hostname instead. This happens regardless of whether I use lowerca ...

Capture a section of the body background to incorporate into the canvas space

As a newcomer to the world of canvas, I have been learning from various sources about how it works. However, my goal is more dynamic and unique than what I've seen so far. I am looking to create a body background for my webpage that is responsive, cen ...

Tax calculator that combines item prices and applies tax multiplication

Struggling to crack the code for my calculator. Despite consulting my textbook, I can't seem to figure out why it won't calculate properly. Any advice or tips would be greatly appreciated. <html> <head> <title> Total Calculator ...

Node Pagination and Filtering feature malfunctioning

I am currently working on incorporating Pagination and Filtering in the backend functionality. This controller receives input such as Page number and Filtering conditions. Controller:- const getPosts = asyncHandler(async (req, res) => { const { ...

Experimenting with throws using Jest

One of the functions I'm testing is shown below: export const createContext = async (context: any) => { const authContext = await AuthGQL(context) console.log(authContext) if(authContext.isAuth === false) throw 'UNAUTHORIZED' retu ...

Show fixed div at specific height

Is there a way to have a fixed title in a DIV that only displays once the user scrolls to the relevant section on the website? I'm looking for a solution where the DIV is hidden until the section is reached during scrolling. ...