Retrieve the corresponding value from the array based on the input value

I have an array that looks like this:

var daysArray = [
    { DayValue: '10D', DayDisplay: '10' },
    { DayValue: '20D', DayDisplay: '20' },
    { DayValue: '30D', DayDisplay: '30' }
]

Now, there is code that does the following.

var selectedDay = getDayDetails('10D')

This code retrieves the value '10D' and checks for its corresponding DayDisplay in the daysArray.

The expected final value of selectedDay is '10'

Similarly, if

var selectedDay = getDayDetails('20D')
, I would expect the final value to be '20'

Could someone please explain how to achieve this?

Answer №1

Employ a filtering method:

function extractDayInfo (input) {
    if(extractDay.length) {
        var result = extractDay.filter(function(selected){
            return selected.DayValue === input;
        });
        if(result.length) return result[0].DayDisplay;
        else return null;
    } else return null;
}

Answer №2

Using _.find is the recommended method for solving this problem

function extractDayInfo(input){
    return _.find(dayInformation,{'day':input});
}
function displayDayInfo(input){
    return _.find(dayInformation,{'name':input});
}

LIVE DEMO

Answer №3

Easy peasy:

function retrieveDay(dayValue) {
    const selectedDay = daysArray.find(d => d.DayNumber === dayValue);
    return selectedDay && selectedDay.DayName;
}

Answer №4

If I'm interpreting your inquiry correctly, there are various approaches to achieve this task. One of the simpler (though not necessarily optimal) methods would involve using a FOR loop to iterate through the array and evaluate the object's properties at each index until finding the correct one.

An example implementation might look like this:

function findDayDetails (value) {
    for (var index in daysArray) {
        if (daysArray[index].dayValue === value) return daysArray[index].dayDisplay;
    }
}

This function could likely be refined further, but it should provide a starting point based on what you're looking for.

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

Utilizing Node.js and Express to create router instances integrated with a database functionality

My understanding from researching the Express documentation is that when declaring an express.Router(), it creates a single instance of a router where you can assign a routing path and execute logic. The concept of a router being like a mini-app for specif ...

Exploring the process of retrieving a pre-defined array within AngularJS

I'm encountering a challenge with accessing the array element in AngularJS. Here is the array: $scope.salesentry = [ { sales_id:'', product_id: '', product_category_id:'', sale_qty:nul ...

The Kendo Refresh function (DropDownList.refresh()) is malfunctioning due to the error of being undefined

When attempting to refresh the Drop Down List after another DropDownList has been changed, I encounter an error stating that the Refresh() method is undefined. As a result, I tried reading the DataSource again and it appears to be loading, but the data rem ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

Unable to access URLs manually

Each time I try to enter a url manually into my browser for an Angular-based website, I always encounter the following error: 'HTTP 404 The resource cannot be found Requested URL: /register' The only functional url is http://localhost:XXXX/in ...

Automate Browsing: Iterating Through Webdrivers in Python

I've been trying to initiate multiple instances of Chrome using Selenium, but every time I attempt to loop through the webdrivers, Selenium shuts them down. Take a look at the code snippet below: from selenium import webdriver user = str(input("Are ...

Issues arising from TypeScript error regarding the absence of a property on an object

Having a STEPS_CONFIG object that contains various steps with different properties, including defaultValues, I encountered an issue while trying to access the defaultValues property from the currentStep object in TypeScript. The error message indicated tha ...

Is there a way to dynamically integrate the Insert Column feature into the ContextMenu of a Syncfusion Treegrid?

What is the best way to add Insert Column functionality to the ContextMenu of a Syncfusion Treegrid? Insert Column Rename Column Delete Column ...

Trigger a jQuery function upon clicking a button

I am attempting to create a jQuery function that can be called independently, and then trigger the function when a click event occurs. Below is the code I have put together: HTML: <input type="text" class="form-control email_input" name='email&ap ...

What benefits do Adobe Creative Cloud apps offer for developing interactive content in AEM?

My client recently transitioned to AEM for their website, and we are tasked with creating an interactive HTML5 'component' to be embedded on a page. While we have previously used custom HTML5 for components, integrating them into pages on the old ...

The Angular application must remain logged in until it is closed in the browser

Currently, my Angular app includes authentication functionality that is working smoothly. The only issue is that the application/session/token expires when there is no user activity and the app remains open in the browser. I am looking for a solution wher ...

AngularJS: In order for ng-model to correctly bind, the child input directive must be compiled within the scope of its parent directive

In order to streamline our contact forms used across multiple applications, we are developing a set of directives to enhance the view's clarity and minimize repetition of default values, validation rules, and structure. Our main objectives include: ...

When the form is submitted, the text input vanishes and then the page is refreshed using AJAX technology

Can anyone help me troubleshoot why my page is reloading even though I used AJAX, and how to prevent it from clearing my input text after clicking the submit button? I tried using the show method to resolve this issue but it didn't work. <form met ...

Only trigger the onclick event once

Can anyone assist me with a function? The onclick event only triggers once. launchTagManager: function(id) { console.log(document.getElementById('metadata_field_multiple_text_701889_options['+id+']')); document.getElementById( ...

Verify whether the elements of the first array are present in the second array, and display the results

Verify whether the second array includes the elements from the first array and display them, otherwise show the elements from the second array that are not in the first one. var contacts = [{name:'muzz',no:1},{name:'muzamil',no:2},{nam ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Is there a way to access Yahoo mail inbox without the user interface?

Exploring various API search options and resources including SerpWow, SERP API, ProgrammableWeb API for Yahoo Search. Experimenting with API token authentication as well. ...

Steps for extracting text from a web element1. Identify the specific web

Hidden within this page is a text box that is not visible in the HTML source code but can be seen on the user interface. Here is the code for the text box: > <textarea id="emails-list" class="ng-pristine ng-valid ng-valid- > required" as-email-l ...

What is the method to have the console display false when the phrases are not in the correct sequence? Node.js

The existing code currently outputs true when message == 'john hi', but I require it to output false when the words are not in the correct order. In this scenario, elements from array1 should precede elements from array2. Additionally, I should ...

Vue.js does not support the usage of external JSON files directly within HTML documents

I'm encountering issues fetching data from an external JSON file for a specific variable. I suspect that the problem lies in using Vue.js within the HTML, as it seems to be having trouble interpreting my code correctly.:joy: jsfiddle Additionally, I ...