Load JSON data in Javascript with the condition where the 'id' is equal to 'x'

I have a coding dilemma where I need to extract specific information from a .json file in JavaScript and load it into an array.

    function loadContacts(filter) {
    var contacts = (function () {
     var contacts = null;
     $.ajax({
        'async': false,
        'global': false,
        'url': 'userdata/' + username + '.json',
        'dataType': "json",
        'success': function (data) {
            contacts = data;
        }
    });
   return contacts;
   })();

  //filter code goes here, not necessary for this example

  }

In my case, I have a user ID number stored as a variable (userid = 99). The example .json file I am working with looks like this:

[{"firstName":"Ryan","lastName":"Butterworth","id":"99"},{"firstName":"John","lastName":"Doe","id":"101"}]

My challenge is to modify the loadContacts function above so that it only retrieves the information from the .json file where the id matches 99. This means the function should return

{"firstName":"Ryan","lastName":"Butterworth","id":"99"}
and store it in the contacts array.

Answer №1

If you want to accomplish this task, filter() is the perfect method...

items = items.filter(function(item) {
    return item.status === "active";
});

It creates a new array by examining each element in the original array and only including those that meet the specified condition.

I won't delve into the synchronous vs asynchronous debate at this moment, but my opinion may be evident from this response :p

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

Locate a specific option that matches the value of the selected data-status and set it as "selected" using jQuery

Currently, I am facing an issue where I need to load 2 separate ajax responses into a select dropdown. The select dropdown will have a data-status attribute, and my goal is to loop through the options to find the one that matches the value of the select da ...

Converting a list into JSON format using R

Let's consider a scenario where I have a collection named "ls" with the following attributes: ls=list(samples=c("a", "b"), id=c("sample_id", "sample_id"), project="p1", date="202202 ...

JavaScript fails to accurately arrange list items

Within my array of objects, I have a list of items that need to be sorted by the fieldName. While the sorting generally works fine, there are certain items where the sorting seems off and does not function properly. Here is the code snippet responsible fo ...

Troubleshooting: Why Laravel 5 VueJS Integration is Failing

I have recently set up a Laravel project and am attempting to integrate Vue.js into it. After running the following commands in my terminal: npm install npm run dev The commands executed without any errors. However, when I tried to import the default Vue ...

Challenges encountered with extracting information from a JSON dataset

When I make an Ajax POST request, the response I receive is structured like this: { "columns": [ "r" ], "data": [ [ { "extensions": {}, "start": "http://localhost:7474/db/data/node/27 ...

Clustering JSON documents with the power of Machine Learning

Looking to conduct document clustering using JSON String data containing various key-value pairs of String and Number types. The goal is to cluster documents based on similar types of keys and values. For example, consider the following JSON Document: {" ...

Is it possible to include choices in the number option for slash commands in discord.js v13?

I am currently working on creating a custom slash command that includes a numerical option. Utilizing the .addNumberOption() method for this purpose. Is there a method to restrict users from inputting numbers outside the range of 0-5 after entering the Di ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

React component allowing for the reuse of avatars

As a novice in React, I've encountered a challenge. My goal is to develop a simple reusable component using MUI. Specifically, I aim to create an avatar component that can be easily customized with different images when called upon. I want the flexibi ...

How about conducting unit tests for a JSON formatter?

Currently, I am in the process of developing a library that has the ability to take a JSON string and format it based on a template and specification selected by the user. Lately, I have begun writing Unit Tests for this library and have encountered diffi ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

"Enhance your Django website with a dynamic voting button using AJAX

I am working on a project where I have implemented the following code: (r'^oyla/(\d+)/$', oyla), Here is the view associated with this code snippet: @login_required def oyla(request, id): if request.is_ajax(): entry = Entry.ob ...

Stringification will not work on the virtual object that has been populated

Here is the object passed to the view: app.get('/view_add_requests', isLoggedIn, function (req, res) { var my_id = req.user._id; // this is the senders id & id of logged in user FriendReq.find({to_id: my_id}).populate('prof ...

Guide to configuring environment variables with Script [Node.js]

Is there a way to set an environmental variable using a script in node.js? I have a script that gives me the deployed solidity contract address and I need to use it in my .env file (I am using the dotenv module). I have been trying to figure out a way to ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

React: Using Chart.js to visualize negative values with a different color in the area

I am implementing a line chart using Chart.js and react-chartjs-2 to display positive and negative values. For positive values, I want the filled area to be green, and for negative values, I want it to be red. Check out the code here import React from &qu ...

Azure PowerShell encounters issues with validating deployment templates, leading to a failure related to Jtoken

While using Powershell and a template file to deploy multiple virtual machines one at a time, I keep encountering this error: New-AzResourceGroupDeployment : 9:27:40 AM - Error: Code=InvalidTemplate; Message=Deployment template validation failed: 'Tem ...

How to incorporate text into the white circle object using three.js

View the current state of my project on this JS Fiddle. I am looking to incorporate rotating text, whether in 3D or 2D. The text should rotate in sync with the white circle. I am open to any method that achieves the desired outcome. Below is the provided c ...

Mongooses provide a JSON list of tags that are defined as subdocuments

I've been struggling with a problem for the last four days. I have a schema and subdocument schema set up like this: var mongoose = require( 'mongoose' ), Schema = mongoose.Schema; var ProjectSchema = new Schema({ name: String, ...

Tips for resolving the ExtPay TypeError when using Typscript and Webpack Bundle

I am currently trying to install ExtPay, a payment library for Chrome Extension, from the following link: https://github.com/Glench/ExtPay. I followed the instructions up until step 3 which involved adding ExtPay to background.js. However, I encountered an ...