JavaScript User Information Lookup Module

My goal:

I am trying to create a function that will check if the firstName provided matches an existing contact's firstName in the contacts array, and if the prop specified is a valid property of that contact.

If both conditions are met, the function should return the value of that property.

If the firstName does not match any contacts, the function should return "No such contact".

If the prop does not correspond to a valid property, the function should return "No such property".

This is my code:

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];

function lookUpProfile(firstName, prop){
// Start function
  for (var i = 0; i<contacts.length; i++){
if(contacts[i].hasOwnProperty("firstName") === true && contacts[i].hasOwnProperty(prop) === true){

  return contacts[i][prop];
}
  else if(firstName !== contacts[i].firstName) {
    return "No such contact";
  }
   else if(!contacts[i].hasOwnProperty(prop)){
     return "No such property";
   }
  }
// End function
}

lookUpProfile("Akira", "likes");

Answer №1

If you want to find a specific contact based on their firstName, you can utilize the Array.prototype.find method - check out the example provided below:

// Data Setup
var contacts=[{"firstName":"Akira","lastName":"Laine","number":"0543236543","likes":["Pizza","Coding","Brownie Points"]},{"firstName":"Harry","lastName":"Potter","number":"0994372684","likes":["Hogwarts","Magic","Hagrid"]},{"firstName":"Sherlock","lastName":"Holmes","number":"0487345643","likes":["Intriguing Cases","Violin"]},{"firstName":"Kristian","lastName":"Vos","number":"unknown","likes":["Javascript","Gaming","Foxes"]}];

function findContact(firstName, prop) {
  var found = contacts.find(function(e){
    return e.firstName === firstName;
  });
  if(!found) {
    return "No matching contact";
  } else {
    if(prop in found) {
      return found[prop];
    } else {
      return "Property not found";
    }
  }
}

// Test with different values
var result = findContact("Akira", "likes");
console.log(result);

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

Tips for adding event listeners to dynamically-loaded content using AJAX

I need help with the following code snippet: $("#contantainer").load("some_page.txt"); Inside some_page.txt, I have the following content: <div class="nav"> <ul id="nav_ul"> <li><a class="nav_a" href="#home" id="home"> ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

Guide to making two text boxes with SimpleDialog in jQuery Mobile

I came across the link below, but unfortunately it's not working for me. jQuery Mobile SimpleDialog with two Inputs? Is there anyone who can assist me after reviewing the code snippet provided below? <script type="text/javascript> ...

Is there a way to incorporate page animations when utilizing the <a href> tag in HTML?

I have created several HTML files. On the main page, I simply inserted some code like this: <a href="new.html> <img src="img/button" id="buttonid"> </a> When I click the button, it takes me to the new.html page. I would like ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...

What is the best way in jQuery to display a particular div with a unique id when a link is clicked?

I have a div with the following structure: <article id="#pippo">blablabla</article> which I have hidden using jQuery $('article').hide(); Now, I want to create a link menu that displays a specific article id when it's clicked ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

difficulty receiving the information promptly via an AJAX request (utilizing AJAX and the 'for' loop)

Currently, I am successfully retrieving data from an ajax call for individuals. However, my next task is to retrieve multiple sets of data simultaneously. Here is the code snippet: for(var i = 1; i <= 2; i++){ console.log(i); $.ajax({ url: cal ...

What is the process for modifying a Gist on GitHub?

Trying to update my Gist from another website using my gist token has been unsuccessful. Retrieving a gist with GET was successful, but updating it with PATCH is not working. I don't believe authentication is the issue since retrieving the gist displ ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), ...

Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } } I want to transform this string into JSON structure like below: { "DataError": { "user_id": [ [Object] ] } } Is there a potential method to achieve this outcome from incorrectly formatted JSON string? ...

Issue with Guild Member Add functionality in discord.js is not functioning as expected

I'm facing an issue with my code where the bot does not send a welcome message when a user joins, despite having everything set up correctly. Even when a user leaves, there is no farewell message being sent either. Here is the code I am using: bot.on ...

Styling the file input type in AngularLearn how to customize the

I've come across numerous queries on how to style an input type file, but I'm struggling to implement it in an angular context. So, what is the best way to customize the appearance of an input type file within an angular application? Below is t ...

Transform basic text into nested JSON structure with JavaScript

There is a plain string in my possession which contains various conditions. const optionString = '{2109} AND ({2370} OR {1701} OR {2702}) AND {1234} AND ({2245} OR {2339})'; The goal is to transform this string into an object structured as foll ...

A router that has numerous parameters will not function properly with express.static

I successfully created an express router with the parameter 'router.get('/add')' and it is working perfectly. However, when I added 'router.get('/edit/:id')', the express.static feature stopped working, causing issue ...

The JOI validation process is failing to return all error messages, even though the "abort early" option

I have been encountering an issue while trying to validate my payload using a joi schema. Instead of returning the errors specified in the schema, only one error is being displayed. Even when I provide a payload with name as "int", it only shows one custom ...