Can we verify the state of a value in an object and simply get back the corresponding key?

In a function, I have an object that contains a mix of letters and numbers. The function is designed to take in an array of numbers, and then run a for-in loop that checks if any of the values in the array match the numbers stored in the object. If a match is found, the function should return only the corresponding letter key.

For example, calling switcher(['26']) should return 'a'. Is achieving this outcome possible?

function switcher(x){
  const letters = {
    a: '26',
    b: '25',
    c: '24',
    d: '23',
    e: '22',
    f: '21',
    g: '20',
    h: '19',
    i: '18',
    j: '17',
    k: '16',
    l: '15',
    m: '14',
    n: '13',
    o: '12',
    p: '11',
    q: '10',
    r: '9',
    s: '8',
    t: '7',
    u: '6',
    v: '5',
    w: '4',
    x: '3',
    y: '2',
    z: '1'
};
}

I've tried using the ES6 map() method to accomplish this task, but I'm unsure about what logic to include within my if statement. Here's what I have so far:

return x.map(function(number){
  let keys = Object.keys(letters);
  for(var key in letters){
    if(letters[key] === number){
    }
  }
 });
}

Do you know of a simpler way to achieve this functionality?

Answer №1

To obtain the corresponding key for a given value, you can utilize both Object.keys and Array#find.

const names = {john:'26',mary:'25',sam:'24',dave:'23',emily:'22',frank:'21',gina:'20',harry:'19',izzy:'18',jenny:'17',kevin:'16',lisa:'15',mike:'14',nora:'13',oliver:'12',patty:'11',quinn:'10',ryan:'9',sandy:'8',tom:'7',ursula:'6',violet:'5',will:'4',xander:'3',yvonne:'2',zara:'1'};

function converter(num){
  var result = Object.keys(names).find(k => names[k] == num);
  return result;
}

console.log(converter('26'));
console.log(converter('9'));

Answer №2

My recommendation would be to simply switch the key/value pairs and proceed from there.

If you need a code snippet to perform the swap, you can achieve it in a single operation (assigned to numbers Map). The following is ES6 syntax:

const animals = {dog:'4',cat:'7',bird:'12',fish:'18'};
const numbers = new Map(Object.keys(animals).map( k => ([animals[k], k])));

console.log(numbers.get('4'));
console.log(numbers.get('18'));

Answer №3

All you have to do is use the code return key;

function converter(x) {
  const letters = {
    a: '26',
    b: '25',
    c: '24',
    d: '23',
    e: '22',
    f: '21',
    g: '20',
    h: '19',
    i: '18',
    j: '17',
    k: '16',
    l: '15',
    m: '14',
    n: '13',
    o: '12',
    p: '11',
    q: '10',
    r: '9',
    s: '8',
    t: '7',
    u: '6',
    v: '5',
    w: '4',
    x: '3',
    y: '2',
    z: '1'
  };
  return x.map(function(num) {
    let keys = Object.keys(letters);
    for (var k in letters) {
      if (letters[k] === num) {
        return k;
      }
    }
  });
}
console.log(converter(['26']));

However, if you find yourself doing this often, it's recommended to use one of the other solutions with the inverted object.

Answer №4

Another approach could be;

function alternativeSwitcher(y){
var characters = {
    a: '26',
    b: '25',
    c: '24',
    d: '23',
    e: '22',
    f: '21',
    g: '20',
    h: '19',
    i: '18',
    j: '17',
    k: '16',
    l: '15',
    m: '14',
    n: '13',
    o: '12',
    p: '11',
    q: '10',
    r: '9',
    s: '8',
    t: '7',
    u: '6',
    v: '5',
    w: '4',
    x: '3',
    y: '2',
    z: '1'
  };
    for (var letter in characters) if (characters[letter] === y) return letter;
    return undefined;
}

console.log(alternativeSwitcher("14"));

Answer №5

It seems like you're interested in obtaining multiple results since you're utilizing an array for your search. For instance, if you input ["26", "5"], the expected output would be ["a", "v"].

You can achieve this with a concise one-liner:

const letters = {a:'26',b:'25',c:'24',d:'23',e:'22',f:'21',g:'20',h:'19',i:'18',j:'17',k:'16',l:'15',m:'14',n:'13',o:'12',p:'11',q:'10',r:'9',s:'8',t:'7',u:'6',v:'5',w:'4',x:'3',y:'2',z:'1'};;

const search = ["26", "5"];
const results = Object.entries(letters).filter(l => search.includes(l[1])).map(l => l[0]);

console.log(results);

This code is compatible post-ES6 era. (Array#includes belongs to ES2016; Object.entries falls under ES2017.) It's easily polyfillable nonetheless.

Object.entries generates an array where each object property serves as an element in the array structured as [key, value], such as ["a", "26"]. These elements are then filtered by matching them against our search array using includes. Finally, we utilize Array#map to extract only the second element from each array, which corresponds to the values from the original array.

Answer №6

Forget about using that lookup table letters (which is actually not even needed for your specific purpose). Instead, opt for utilizing the charCodeAt and fromCharCode methods for converting letters to numbers and vice versa:

function switcher(x) {
   return x.map(function(code) {
       return x > 0 && x <= 26 ? String.fromCharCode(123-x) : "";
   });
}
console.log(switcher([26, 1])); // ["a", "z"]

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

Retrieve information about a parent's data related to child events in Vue.js

I'm working with two components nested inside each other. The parent component has a click event that needs to modify the data value of the child component. <template> <div> ..... ..... <my-component :op ...

What is preventing JSON.parse() from extracting the data from this json string in this particular scenario?

One of the challenges I'm currently facing involves extracting a specific item from a JSON-formatted string and displaying it on the screen using .innerHTML. The JSON string, named myData, is retrieved from a MySQL database via PHP. To achieve this, ...

Mounting a Vue3 component within an established application: Step-by-step guide

Imagine we have already mounted an App in main.js: createApp(App).mount('#app'); Now, I want to create a function that is called like this: createModal({ render: () => <SomeComponent />, }); Typically, we would impl ...

What is the proper method for triggering an animation using an IF statement with A-Frame animation mixer?

I am currently exploring the capabilities of the animation mixer in A-Frame and trying to trigger a specific action when a particular animation is playing (like Animation 'B' out of A, B, C). Although I'm not well-versed in Javascript, I ha ...

Showing a div with a smooth fade-in effect while switching its display property to inline using jQuery

Currently, I am working on a project that involves implementing a "side pop up". To ensure it doesn't flicker like it does with jQuery's "hide()" method, I want to start by setting the display property to none using CSS. My main question is: - Ho ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

Retrieve information from a nested array using JSON and PHP

Can anyone help me retrieve the value of "single_img" from a subarray? $video ='{"msg":"OK","server_time":"2021-12-04 20:33:26","status":200,"result":[{"single_img":"8eybbqf5nn ...

Utilize jQuery.ajaxComplete to identify the location of the AJAX request

I have an event: $(document).ajaxComplete that is functioning perfectly. Yet, I am looking to determine whether ajax took place at a particular spot within the document. Is there a method to identify which ajax call was made? $(document).ajaxComplete(fu ...

Top method for transforming an array into an object

What is the optimal method for transforming the following array using JavaScript: const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; into this object structure: const result = ...

Does JSON hijacking play a role with IE versions greater than 10 or Chrome versions greater than 30?

OWASP suggests wrapping json response with an object rather than returning a direct array. For instance: [{"id":5}] Is this vulnerability still relevant? Could it be exploited? After testing in Chrome, IE, and FF, I couldn't find a way to 'h ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

Using lazy loading and $ocLazyLoad for improved performance

Recently, I stumbled upon the $ocLazyLoad third-party Angular module that allows for the lazy loading of JavaScript files. This concept has me a bit perplexed. Can you explain the difference between lazy loading and caching, and why one would choose to l ...

What is the best way to send a reply from a GET request query on the server side of an express application?

Currently, I am utilizing a query to interact with a Postgres database in order to save the result into a variable within a GET request on the server-side of an Express application. Although my query successfully returns the desired issueID when executed ...

What are the steps to resolving an issue with importing a css file in next.js?

Error: ./node_modules/quill-emoji/dist/quill-emoji.css ModuleParseError: Module parse failed: Unexpected character '�' (1:0) You may need a suitable loader for handling this file type, as there are currently no configured loaders to process it. ...

Including React components in my HTML documents

I have developed a node.js server using express and am rendering an html page with jsx code embedded. The server is running smoothly, but I am encountering difficulties when trying to import other jsx components into my html file to utilize them in my main ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

Not every item in the array has been allocated to the model

I am encountering an issue with loading all the elements of an array from my ExpressJS backend to my frontend framework OpenUI5. Despite having an array of 520 elements, only the first 100 elements are being loaded into the model. How can I ensure that all ...

The switch statement is not functioning properly when the button is pressed

I am trying to trigger an alert inside a switch statement when I click a button, but for some reason, it is not working. Even if I simply have an alert in the previous function, there is no output on my website. What could be causing this issue? Here is ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...