Is there a functional way in JavaScript/ES6 to retrieve a specific object from an array based on its property or field value?

I've got a JavaScript array filled with objects, which in this case represent different countries pulled from JSON data via a web service:

let countries = [
    ...,
    {
        "id": 46,
        "type": "COUNTRY",
        "name": "Cape Verde",
        "isoCode": "CV",
        "isoNbr": "132"
    },
    {
        "id": 52,
        "type": "COUNTRY",
        "name": "Christmas Island",
        "isoCode": "CX",
        "isoNbr": "162"
    },
    {
        "id": 63,
        "type": "COUNTRY",
        "name": "Cyprus",
        "isoCode": "CY",
        "isoNbr": "196"
    },
    {
        "id": 64,
        "type": "COUNTRY",
        "name": "Czech Republic",
        "isoCode": "CZ",
        "isoNbr": "203"
    },
    {
        "id": 88,
        "type": "COUNTRY",
        "name": "Germany",
        "isoCode": "DE",
        "isoNbr": "276"
    },
    {
        "id": 66,
        "type": "COUNTRY",
        "name": "Djibouti",
        "isoCode": "DJ",
        "isoNbr": "262"
    },
    
    ...
];

QUESTION:

What's the most efficient way to retrieve an entry based on its isoCode value within this array?

Would converting this into a map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) beforehand, using isoCode as the key and the object itself as the value, be a good approach...??

let mapOfCountries = turn_into_map(countries);

selectedCountry = mapOfCountries[this.selectedEntity.countryCode];

// or even simpler:
// selectedCountry = mapOfCountries['DE'];

What is the most effective way to achieve this in JavaScript / ES6? Any thoughts on applying a functional methodology here instead of resorting to a manual loop check? Not really keen on the traditional for loop method. Yuk.

Answer №1

If you're looking to create a map using JavaScript, one useful method is Object.fromEntries. This allows you to easily access specific elements in the map by their country code. Here's an example:

const mapOfCountries = Object.fromEntries(
  countries.map(o => [o.isoCode, o])
);
console.log(mapOfCountries['DE'])

let countries = [
   { id: 46, type: "COUNTRY", name: "Cape Verde", isoCode: "CV", isoNbr: "132" },
   { id: 52, type: "COUNTRY", name: "Christmas Island", isoCode: "CX", isoNbr: "162" },
   { id: 63, type: "COUNTRY", name: "Cyprus", isoCode: "CY", isoNbr: "196" },
   { id: 64, type: "COUNTRY", name: "Czech Republic", isoCode: "CZ", isoNbr: "203" },
   { id: 88, type: "COUNTRY", name: "Germany", isoCode: "DE", isoNbr: "276" },
   { id: 66, type: "COUNTRY", name: "Djibouti", isoCode: "DJ", isoNbr: "262" }
];

const mapOfCountries = Object.fromEntries(
  countries.map(o => [o.isoCode, o])
);

console.log(mapOfCountries['DE']);
console.log(mapOfCountries['CZ']);

Answer №2

To easily find an element in an array, you can simply use the find() method:

const countries=[{id:46,type:"COUNTRY",name:"Cape Verde",isoCode:"CV",isoNbr:"132"},{id:52,type:"COUNTRY",name:"Christmas Island",isoCode:"CX",isoNbr:"162"},{id:63,type:"COUNTRY",name:"Cyprus",isoCode:"CY",isoNbr:"196"},{id:64,type:"COUNTRY",name:"Czech Republic",isoCode:"CZ",isoNbr:"203"},{id:88,type:"COUNTRY",name:"Germany",isoCode:"DE",isoNbr:"276"},{id:66,type:"COUNTRY",name:"Djibouti",isoCode:"DJ",isoNbr:"262"}];

console.log(countries.find(c => c.isoCode === 'DJ'))

Additionally, I recommend exploring the link provided as it offers a wealth of resources on JavaScript. It's definitely worth delving into for some interesting insights :)

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

Detecting errors in asynchronous functions within other asynchronous functions

I'm attempting to capture errors in nested asynchronous functions to perform a rollback if an error occurs. Initially, I have a try-catch block where I call a function that then calls another function. The final function should throw an error, and I ...

Error message displayed when attempting to render a D3.js geoPath map: <path> attribute d is expecting a number

Currently struggling with creating a map using D3.js The given code functions properly with certain JSON files, but when I try to use the necessary data, it's throwing a series of errors like this: Error: attribute d: Expected number, "….21 ...

Creating a custom Object class in THREE.js that handles imported meshes

Hey there, I'm just getting started with THREE.js and I'm trying to create a custom class that extends THREE.Mesh for my scene. My goal is to have the class contain an imported mesh via JSON loader, but so far all my attempts have not been succes ...

Is there a way to display the items I've added to my cart when I click on it?

I have a collection of product IDs stored in local storage. I am using these IDs to populate the list of products added to the basket. Strangely, when I navigate to the basket page, the products do not appear unless I make a small code modification or re-s ...

Changing tabs will redirect the url

Having an issue with ASP AjaxControlToolkit tabs. I want the URL to change based on the tab selected by the user. Check out the code snippet below: <asp:TabContainer ID="TabContainer1" runat="server" Width="100%" Height="100%"> <asp:TabPanel ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

Challenges with Asset Management in Vite Compilation Result

I'm encountering a problem with structuring assets in the output directory while utilizing Vite for my project. I have set up the output.assetFileNames option to categorize assets into subfolders based on their types (css, fonts, img, js), but it&apos ...

Implementing a file size restriction in C# when writing a lengthy JSON string using the System.IO.Stream

I have a large array stored in Json format, and the result is saved in a variable called "sz" (string). However, when I attempt to save this Json result (string sz) to a file, it seems that not all of the string gets saved. Why is this happening? The siz ...

Tips for declaring and utilizing multiple functions within an Angular JS Factory, as well as executing one function inside another

Could someone assist me in creating multiple functions within an AngularJS Factory? I am looking to access the returned value from one function and process it in another function. I attempted the code below without success. In the following function, I wa ...

Retrieving the value of an inputtext component in PrimeFaces using jQuery

I have the following code snippet: <h:form id="calcForm"> <h:panelGrid columns="3" styleClass="panelGridNoBorder"> <p:inputText id="value" /> <p:commandButton value="calculate " onclick="calc()" /> </h:panelGrid> ...

JavaScript: Locate a property and its corresponding value within a JSON object

Dealing with a JSON object that varies in structure, but always contains a key. Any suggestions on how to extract this information? For example: "Records": { "key": "112" } Or "Records": { "test": { "key": "512" } } Or even within ...

Display dropdown with multiple lists using LocalStorage

I'm facing an issue with displaying a list in a dropdown multiple using LocalStorage. The problem arises after saving data to LocalStorage and then going back to my modal. The saved list does not show up in the dropdown. I simply want to display the l ...

calculating the maximum sum of a continuous subarray by using recursion to produce the final outcome

Is it possible to recursively find the largest sum contiguous subarray and have the function directly return the output? My current solution involves storing the maximum subarray ending at each index and then finding the largest among those in the print() ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

What is the process for fetching and storing a binary file video in Flask's Blob?

I've been dealing with a video encoding issue for the past few days and I need some help. Objective: Capture a video from my laptop's webcam using a VueJS frontend application. Send this video to a Python Flask app on the backend via FormData u ...

JavaScript method not properly sorting the last nested array

I am having trouble with sorting the last nested array using arr[i].sort(). Despite trying various methods such as FOR and WHILE loops along with different operators, I still cannot achieve the desired result. Can someone help me identify what I am doing w ...

Accessing id3 v2.4 tags using the built-in capabilities of Chrome's Javascript FileReader and DataView

After discovering the solution provided by ebidel, individuals can extract id3v1 tags using jDataView: document.querySelector('input[type="file"]').onchange = function (e) { var reader = new FileReader(); reader.onload = function (e) { ...

Sweet Alert seems to be malfunctioning within ajax requests in a Django environment

Experience Soothing Notifications - I’ve incorporated Sweet Alert into my project by using a CDN in the base HTML file: <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> While attempting to utilize Sweet ...

Implement intro.js on a bootstrap dropdown component

I'm having difficulty using intro.js with dropdown elements. I came across a similar question on this topic with no answer: IntroJS Bootstrap Menu doesnt work If you want to see the error in action, follow these steps: Click on "Aide" (The green bu ...