Optimal method for retrieving data from a JSON object using the object's ID with a map

Can you teach me how to locate a json object in JavaScript?
Here is a sample Json:


{
"Employees" : [
{
"userId":"rirani",
"jobTitleName":"Developer",

"preferredFullName":"Romin Irani",
"employeeCode":"E1",
"region":"CA",
"phoneNumber":"408-1234567",
"emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfadb0b2b6b1f1b4f1b6adbeb1b69fb8b2beb6b3f1bcb0b2">[email protected]</a>"
},
{
"userId":"nirani",
"jobTitleName":"Developer",    
"preferredFullName":"Neil Irani",
"employeeCode":"E2",
"region":"CA",
"phoneNumber":"408-1111111",
"emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa4afa3a6b8a3b8aba4a38aada7aba3a6e4a9a5a7">[email protected]</a>"
}
]
}

In the above JSON, I want to search for a specific userId based on employeeCode, emailAddress, and PhoneNumber. Currently, my approach is as follows:


for(var i=0; i<json.length;i++){
       if((employeeCode==code)&&(emailAddress ==email)&&(PhoneNumber==phone)){
                     //here i am getting userId
        }   
    }

I'm not sure if this method is correct. It works fine for small sets of data, but what should I do if I have a large amount of data to search through?

Answer №1

To extract specific user information from the array of Employees, you can effectively utilize the map function:

var data = {
"Employees": [
{
"userId": "rirani",
"jobTitleName": "Developer",
"preferredFullName": "Romin Irani",
"employeeCode": "E1",
"region": "CA",
"phoneNumber": "408-1234567",
"emailAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2809d9f9b9cdc99dc9b80939c9bb2959f939b9edc919d9f">[email protected]</a>"
},
{
"userId": "nirani",
"jobTitleName": "Developer",
"preferredFullName":"Neil Irani",
"employeeCode": "E2",
"region": "CA",
"phoneNumber": "408-1111111",
"emailAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="442a212d28362d36252a2a2d042329252d286a272b29">[email protected]</a>"
}
]
};

var code ='E2' , email ='<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa1aaa6a3bda6bdaea1a68fa8a2aea6a3e1aca0a2">[email protected]</a>' , phone = '408-1111111', userId;
data.Employees.map(x=>{
   if(x.employeeCode == code && x.phoneNumber == phone && x.emailAddress== email){
     userId = x.userId;
  }
});

console.log(userId);

Answer №2

To locate specific information within an array, utilize the find method along with a custom callback function.

When using the find() method, the first element in the array that satisfies the testing function will be returned. If no such element is found, undefined is returned.

let emailAddress="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc929995908e958e9d9295bc9b919d9590d29f9391">[email protected]</a>";
let phone="408-1111111";
let code="E2";
let Employees = [
{
"userId":"rirani",
"jobTitleName":"Developer",
"preferredFullName":"Romin Irani",
"employeeCode":"E1",
"region":"CA",
"phoneNumber":"408-1234567",
"emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12607d7f7b7c3c793c7b60737c7b52757f737b7e3c717d7f">[email protected]</a>"
},
{
"userId":"nirani",
"jobTitleName":"Developer",    
"preferredFullName":"Neil Irani",
"employeeCode":"E2",
"region":"CA",
"phoneNumber":"408-1111111",
"emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="345a515d58465d46555a5d745359555d581a575b59">[email protected]</a>"
}
];
let employee=Employees.find(function(employee){
    return employee.emailAddress==emailAddress && employee.phoneNumber==phone && employee.employeeCode==code;
});
console.log(employee.userId);

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

Instructions for activating column resizing in MUI DataGrid

Is there a way to enable column resizing for users in MUI DataGrid? It's enabled by default on XGrid, but I would like to enable it on Datagrid as well. Any assistance is appreciated. <DataGrid className={classes.table} ...

Using Node.js to Send Parameters in a POST Request

I have a node.js application with an express framework and a POST route defined as follows: app.post('/test', function(req, res){ //res.send(req.body.title + req.body.body) console.log(req.params); console.log(req.body); console.log(req.bod ...

Encountering an issue with the v-carousel component from Vuetify: receiving a 'Cannot read property 't' of undefined' error message

Currently, I am trying to create an image carousel using Laravel along with Vue/Vuetify. The issue lies in the fact that the Vuetify v-carousel and v-carousel-item components are not rendering properly due to the error mentioned in the title. I have alrea ...

Attempting to incorporate regular expressions into a column within a select statement

I need to extract a list of campaign IDs from JSON stored in a MySQL database (version 5.6.17) using regex. My query is as follows: SELECT JSON REGEXP '"id":([0-9]*)' AS id FROM PROD_APPNEXUS.dimension_json_creatives; The JSON column contains ...

What happens when Angular elements don't have an injector?

Exploring Angular's custom elements while steering clear of dependency injection is my current experiment. const MyElementElement = createCustomElement(MyElementComponent, { injector }); customElements.define('my-element', MyElementElement) ...

Adding Roles Using Discord.js - A Simple Guide

I'm currently working on a Discord bot using Discord.js, and I am trying to implement a feature where users can use a command to assign themselves a role. However, despite my best efforts, I am unable to get this functionality to work. In my bot' ...

Retrieve a specific subdirectory from the bundle

I've developed a Typescript package with the following file structure: package.json src/ index.ts common/ index.ts sub/ index.ts My goal is to import certain modules from the package like this: import {...} from '<package>&ap ...

When attempting to retrieve a String value from a JSON object on an Android platform, the process fails if the

Hello Everyone. Currently, I can successfully fetch a JSON object from Alpha Vantage for my currency converter app. However, I am facing an issue in retrieving the specific string value I need (e.g., "5. Exchange Rate": "17.86300000") due to spaces in the ...

Immense trade adhesive navigation bar menu

Currently, I am in the process of enhancing a big commerce website and aiming to implement a sticky menu on scroll. I attempted to use bootstrap along with CSS to achieve this functionality, however, encountered some issues. Below is the snippet of code I ...

Creating seamless shading effects using three.js with Blender integration

When I import a Blender scene into a three.js environment, the curved faces appear flat. Is there a method to ensure that these surfaces remain smooth as intended? Despite calculating vertex normals and activating the smoothShaded option, the issue persis ...

Utilizing several data sources within a single mat-table

Hello, I require assistance with a task. I am trying to display multiple mat-tables with different data sources in my component.ts file Groups(){ this.apiSvc.Cards().subscribe((rsp: any) => { this.groups = rsp; this ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

NextJS does not support the rendering of the map function

Currently, I am getting acquainted with NextJS by creating a basic blog. I have successfully passed the data through props and can see it logged in the console within the map function. However, I am facing an issue where the HTML content does not display i ...

Tips for creating multiple files using nodejs and express

I am currently working on developing a personalized code editor that consists of 3 textareas: html, css, and javascript. The objective is to save the data from each textarea into individual files. With the help of express and nodejs, I have successfully m ...

Troubleshooting Jasmine Unit Testing issues with the ng-select library

Recently, I integrated the ng-select component from Github into my Angular application without encountering any console errors during runtime. It functions as expected; however, issues arise when running unit tests with Jasmine. To incorporate NgSelectMod ...

Tips on removing the backslash character within a JSON key in Java

While I understand the importance of best practices, sometimes we have to prioritize meeting our customer's requirements, even if it means deviating from those practices. I'm sure many of you have been in a similar situation before and can relate ...

What is the best way to access the inner html of every cell within a table row that I have selected?

I want to implement a feature on my website where users can click a "save" button on a specific row in a table and save the entire row's innerHtml onto another page as their favorite hiking trails. I've been trying to achieve this by adding clic ...

What is the method for incorporating parameters into an array filter?

Imagine having an array containing multiple duplicate objects. How can we create a condition to specifically identify objects with certain criteria, such as matching IDs, duplicate status, and duplicate dates? The goal is to only display the object with th ...

Creating a task management system using HTML, CSS, and JavaScript that utilizes local

I have been extensively researching how to create a to-do list using JavaScript with local storage, but unfortunately, I have not been able to find exactly what I am looking for. Is there a way for me to set up a to-do list and input data before actually ...

Error encountered while attempting to render a form within a partial in Rails 5: "simple_fields_for" method is not defined for the SimpleForm::FormBuilder instance

This is a continuation from this thread: Passing a form as a local to a ajax rendered partial in Rails 5 I've searched extensively but haven't been able to find a working solution. Relevant Controller (profits_controller.rb): def new_tabs ...