Exploring an array to retrieve a specific value

Can someone assist me?

I am looking to create a JavaScript function that follows the structure of the code example below. Unfortunately, I do not have enough programming skills to develop a functional solution from scratch.

The goal is to input a value, search through an array using that value, and return the corresponding short name (the value on the right side of the colon character).

function findShortName() {

var filenames = {
        "REQUEST FOR INFO": "REQI",
        "MEDIA CALL": "MC",
        "ISSUES NOTE": "ISN"
    };

EX1.)

    var value_to_search_for = "REQUEST FOR INFO (ALPHA)";

    if (filenames[value_to_search_for]) {

        return filenames[value_to_search_for];

    }

EX2.)
    var value_to_search_for = "MEDIA CALL";

    if (filenames[value_to_search_for]) {

        return filenames[value_to_search_for];

    }

}

Answer №1

You have the option to convert it into an object and proceed with this approach

var filenames = {
  "REQUEST FOR INFO": "REQI",
  "MEDIA CALL": "MC",
  "ISSUES NOTE": "ISN"
};

var getValue = function(val, obj) {
  if (val in obj) return obj[val];
}

console.log(getValue('ISSUES NOTE', filenames));

You can also opt for an array of objects and then you can perform this action

var filenames = [
  {"REQUEST FOR INFO": "REQI"},
  {"MEDIA CALL": "MC"},
  {"ISSUES NOTE": "ISN"}
];

var getValue = function(val, array) {
  array.forEach(function(el) {
    for (prop in el) {
      if (prop == val) console.log(el[prop]);
      }
    });
  }

getValue('MEDIA CALL', filenames);

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

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

Waiting for the forEach loop to complete

One of my express endpoints has a functionality that includes checking the availability of domain names against GoDaddy's API. However, I am struggling with how to properly await the results. My code currently iterates through an array called tlds an ...

Create a unique functionality by assigning multiple event handlers to a single event

I am looking to add a JavaScript function to an event that already has a handler function. The new function should complement the existing one rather than replace it. For instance: There is a function named exFunction() that is currently linked to docume ...

What is the process for deleting an event in Vue?

My Vue instance currently includes the following code: async mounted () { document.addEventListener('paste', this.onPasteEvent) }, beforeDestroy () { document.removeEventListener('paste', this.onPasteEvent) }, methods: { onPasteEv ...

Node.js encountered an SFTP error stating "Error: connect: An existing SFTP connection is already defined."

Working within my node.js application, I have implemented ssh2-sftp-client to upload an image every 5 seconds. The initial upload functions correctly, but upon repeating the process, I encounter an error message: node .\upload.js uploaded screenshot ...

What is the best method for extracting information from this data? (extracting data from

I need assistance. I've written multiple arrays to a text file and now I'm trying to parse them. What am I doing incorrectly? fs.readFile("./data.txt", "utf8", function(error,dataRes){ console.log('Reading data') ...

Tips for using rspec to test front end functionality?

In my Rails project, I have incorporated Vue.js using only the core library. Currently, most forms in the project are developed with Vue.js. When testing front-end features like form filling or validations using feature tests in RSpec, I found it to be qui ...

Trouble with hide/show loop in setTimeout function

I have a special animation with 3 text items that are initially invisible. The goal is to make these items appear one by one with a delay of 2 seconds after clicking a button. Each item should be visible for 1 second before fading out and making way for th ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

Attempting to send a GET request from localhost:8080 to localhost:3000 is proving to be a challenge as I keep encountering a CORS error. Even after trying to install CORS on my node.js server, the issue

While attempting to send an axios GET request from my front-end app on localhost:8080 to my Node.js/Express.js server on localhost:3000, I encountered a CORS error. Despite installing the cors npm package and using it as middleware in my Node.js/Express.js ...

Is the JQuery Mobile .page() method triggering an endless loop?

Creating a dynamic listview with data from an AJAX response has been successful, however, when using JQM's .page() function on it, it appears to enter an infinite loop where the listview keeps getting appended indefinitely. I'm unsure if this is ...

What could be the reason for my inability to retrieve req.user.username with passport.js?

I recently started using passport.js for authentication and I'm encountering an issue. When I log in via Google, the only information available to me through req.user is the user id. I have provided my passport setup code, along with the routes, hopin ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Concealing Components using Angular's ng-change Feature

I need help displaying or hiding an element in a form using ng-change or any other method you suggest. Here is the HTML snippet I am working with: <div ng-app ng-controller="Controller"> <select ng-model="myDropDown" ng-change="changeState( ...

send data to a hyperlink

I need to pass a parameter to the href based on the first name in the list. The names are links to another page that I retrieve via an _id passed in the URL. The issue I am facing is that the id is not being passed to the URL, resulting in an error. How ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

Can VueJS Computed handle multiple filters at once?

I am encountering an issue with this code - when I attempt to add another filter inside the computed section, it doesn't work. However, if I remove the additional filter, the code functions correctly. My goal is to have both company and product searc ...

Attempting to initiate an AJAX request to an API

Hey everyone, I've been working on making an AJAX API call to Giphy but I keep receiving 'undefined' as a response. Can anyone offer some advice on how to troubleshoot and fix this issue? Thanks in advance for your help! var topics = ["Drak ...

The useEffect function is executing two times

Check out this code snippet: import { type AppType } from 'next/app' import { api } from '~/utils/api' import '~/styles/globals.css' import Nav from '~/components/Nav' import { useEffect, useState } from 'react& ...