Display the specific outcome solely from an array using AJAX

I possess an array of objects in JSON format as shown below:

[{"id":"0","NameInData":"","name":"","type":"mf","greeting":"Bonjour","message":"GENERIC: Lorem ipsum."},
{"id":"1","NameInData":"alexis","name":"Alexis","type":"mf","greeting":"Bonjour Alexis","message":"ONE: Lorem ipsum."},
{"id":"2","NameInData":"laurence","name":"Laurence","type":"ff","greeting":"Hello Laurence","message":"TWO: Lorem ipsum."},
{"id":"3","NameInData":"francois","name":"Francois","type":"mm","greeting":"Konnichiwa Francois","message":"THREE: Lorem ipsum."},
{"id":"4","NameInData":"dirk","name":"Dirk","type":"mf","greeting":"Ni hao Dirk","message":"FOUR: Lorem ipsum."},
{"id":"5","NameInData":"coline","name":"Coline","type":"ff","greeting":"high 5! Coline","message":"FIVE: Lorem ipsum."}]}

I can extract the value of a particular key from this array and perform some action with it using the code snippet given below:

function getID(name){

    $.each(data,function(key,value){    

        $.each(value,function(key1,value1){     

            if(value1 == content){    
                console.log(value.id);

                var name = value.name;                  
                $('#nameText').text(name);
                console.log("Name: " + name);

                var greeting = value.greeting;
                $('#greetingText').text(greeting);
                console.log("Greeting: " + greeting);

                return;

            }                   
        });

    });
    
                var name = content;             
                $('#nameText').text(name);
                console.log("Name: " + name);               

                var greeting = data[0].greeting;
                $('#greetingText').text(greeting);
                console.log("Greeting: " + greeting);

                console.log('0');
                return;

}

getID(data);
return false;   

In case the name is not found within the list, I am attempting to perform other actions. However, due to the array containing 6 items, the process repeats 6 times and prints out '0' multiple times. Ideally, I would like to have only one output, where either a name and its id are identified and corresponding information is printed, or the id is set to 0 for unrecognized names.

You can access my complete code at this link. I would appreciate any insights on identifying any syntax errors in my code.

UPDATED CODE BASED ON ANSWER HERE

Answer №1

Using Array.filter() allows you to create a new array with elements from the original array that pass a specific test. In this scenario, the test involves checking if an item's name matches the user-provided name:

success: function(data) {
  var data = data || [];
  var results = data.filter(function(element, index, array) {
    if (element.name === $('#nameText').text(name)) {
      return (true);
    }

    return (false);
  });

  if (results[0]) {
    // An element in the array matched what the user entered
    console.log(results[0]);
  }
  else {
    // No matching name found in the array for $('#nameText').text(name)
    // Set id to 0 or any other value as needed
  }
}

Please note that this code is not flawless; it assumes that $.ajax() always returns an array and there are no duplicate names in the array. Nevertheless, it should provide a good starting point for your implementation.

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

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

What is the mechanism by which sending data directly to the response object displays content to the user?

What exactly does the .pipe(res) segment of the code snippet from that article do at the end of the stream? fs.createReadStream(filePath).pipe(brotli()).pipe(res) I have a basic understanding that the first part reads the file and the second compresses i ...

Shuffling rows and columns in an R array with custom labels

After reading the initial question about converting a 4-dimensional array to a 2-dimensional data set in R by @Ben-Bolker, I am facing a similar problem. I have my own 3D array called 'y' with dimensions [37,29,2635] (representing firms, years, ...

Click to execute instantly without encountering any errors

I'm working with a modal in React JS and I want to trigger a function when the modal opens. I currently have a button function that is functioning correctly using the following code: <button onClick={functionExample("stringParam", true)} ...

PHP MySQL table submission button

Here is the content I have: <table class="sortable table table-hover table-bordered"> <thead> <tr> <th>CPU</th> <th>Speed</th> <th>Cores</th> <th>TDP</th> <th> ...

The Controller is not being accessed by Ajax.BeginForm()

I've encountered an issue with the code below. There are 2 fields and a search button. When I input a value only for the Holiday field and click search, it does not trigger the controller. However, if I provide a value for the Year field, then it hits ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

Take away limitations from JavaScript code

I stumbled upon this code snippet online and I'm attempting to eliminate the Name must be letters only and min 3 and max 20 restriction. The name provided can have less than 3 characters and may include numbers. My JavaScript skills are still in the l ...

Experiencing disconnection from SQL server while utilizing the Express.js API

Im currently working on an API that retrieves data from one database and posts it to another database, both located on the same server. However, I am facing issues with the connections. Initially, everything works fine when I run the app for the first time ...

Creating a horizontal scrolling section for mobile devices using CSS

Looking to create a horizontal scroll area specifically for mobile devices, similar to the design seen here: https://i.sstatic.net/oSNqL.png Additionally, I want to hide the scrollbar altogether. However, when attempting to implement this, there seem to ...

In the world of coding, the trio of javascript, $.ajax,

I need help with iterating over an array and assigning a variable using a for loop. Here is the scenario: function Person(name, status){ this.name = name; this.status = status; } var status = []; var array = ["bill","bob","carl","ton"]; function exAj ...

Analyzing the similarities in properties between two arrays of objects in order to generate a pair of fresh arrays

I have two sets of data represented as arrays: var oldOrder = [{"Id": "10","Qty": 1}, {"Id": "3","Qty": 2}, {"Id": "9","Qty": 2}]; var newOrder = [{"Id": & ...

What's the best way to remove all &#160; siblings from a JSON string using JavaScript?

Is there a way to remove all instances of "&#160;" in a JSON string? { "Cat": "laps&#160;milk", "Dog": "Woofs&#160;at&#160;Postman", "Bird": "Jumps&#160;over&#160;the&#160;river", "I": "Want&#160;to&#160;learn&a ...

How can I prevent a tree node from expanding in ExtJS when double-clicked?

Is there a way to make my treepanel perform a specific action when double clicked? Every time I double click on a treenode, it expands or collapses unintentionally. Is there a method to prevent this expanding or collapsing behavior when double clicking? ...

What is the method to modify filterFilter so that it outputs an array of index values rather than the actual

Is there a way to utilize filterFilter functionality without creating a new array every time it runs? Instead of returning a new array, I'm looking to return an array of indexes and then retrieve the associated items in my service. This approach allow ...

Is there a way to obtain a set of JSON objects from a webpage and then append each item to a row in an HTML table?

My website has a collection of JSON objects arranged in an array as follows: [ { id: 10 name : abc }, { id: 11 name : xyz } ] I am looking to display these elements in an HTML table format, similar to the illustration shown below: https:/ ...

Is it possible to achieve a callback with jQuery after loading?

Currently, I am working with PHP and jQuery and have successfully implemented the following code. $(".design").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{ menu: 'layout', }); This is my desired action. I woul ...

Set Divs in Absolute Position Relative to Each Other

I need to create a simple navigation system using <div> elements as individual pages. The goal is to have "next" and "back" buttons that allow users to switch between these pages with a smooth fade-in and fade-out effect, all powered by jQuery. Howev ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...