Searching for a specific string within a nested array in a JSON object using JavaScript loops

I'm struggling to loop through a JSON array with subarrays to find the user whose username is 'admin'. Once I locate this user, I want to create a new JSON array containing their data (region, sport, city, etc.). I am unsure how to implement this logic within a loop and extract the relevant information. My apologies for the seemingly basic question, but I could use some guidance in this matter.

Here is an example of the JSON array structure:

[
    {
        "_id": "5520f52e2c0a22541541bde1",
        "region": {
            "_id": "551e6779d8f1afa01bd86529",
            "name": "region_name"
        },
        "user": {
            "_id": "551a938af056a7fc099879c1",
            "firstName": "John",
            "lastName": "Boo",
            "username": "admin",
            "id": "551a938af056a7fc099879c1"
        },
        "__v": 0,
        "sport": [
            {
                "_id": "551e69c6d8f1afa01bd86533",
                "name": "Running"
            }
        ],
        "city": "some_city",
        "advert": "some_advert",
        "title": "I want to run!",
        "created": "2015-04-05T08:41:18.173Z"
    },
    {
        "_id": "552010740628cab002b3a700",
        "region": {
            "_id": "551e67b6d8f1afa01bd8652f",
            "name": "region_name"
        },
        "user": {
            "_id": "551a938af056a7fc099879c1",
            "firstName": "Bill",
            "lastName": "Foo",
            "username": "bill_foo",
            "id": "551a938af056a7fc099879c1"
        },
        "__v": 0,
        "sport": [
            {
                "_id": "551e5e01abb74a8423410b88",
                "nazev": "Hockey"
            }
        ],
        "city": "some_city",
        "advert": "some_advert",
        "title": "some_title",
        "created": "2015-04-04T16:25:24.733Z"
    }
]

Edit: the desired output for user 'admin' would be:

[
    {
        "_id": "5520f52e2c0a22541541bde1",
        "region": {
            "_id": "551e6779d8f1afa01bd86529",
            "name": "region_name"
        },
        "user": {
            "_id": "551a938af056a7fc099879c1",
            "firstName": "John",
            "lastName": "Boo",
            "username": "admin",
            "id": "551a938af056a7fc099879c1"
        },
        "__v": 0,
        "sport": [
            {
                "_id": "551e69c6d8f1afa01bd86533",
                "name": "Running"
            }
        ],
        "city": "some_city",
        "advert": "some_advert",
        "title": "I want to run!",
        "created": "2015-04-05T08:41:18.173Z"
}]

Answer №1

Iterate over the array and extract each element associated with a user whose username is admin:

var result = [];
var nameToSearchFor = 'admin';

for(var index = 0; index < arr.length; index++)
{
    var item = arr[index];
    if(item.user.username === nameToSearchFor)
    {
        result.push(item);
    }
}

Answer №2

If you're looking for a solution to your issue, one approach is to locate the index where the username admin exists. In this scenario, it's at index 0 within the provided JSON array. You can retrieve the entire object by referencing the index, as shown below:

var i = 0;
for(; i< json.length; i++){
  if(json[i].user.username === "admin") break;
}

Once you have found the index, you can access the data related to admin like so:

json[i].user.firstName

You can view a live example in this plunk here

UPDATE If you only wish to extract that specific slice into a new array, you can simply use the slice method with the acquired index.

var newArray = json.slice(i, i+1);

Answer №3

Utilizing an open source tool such as jinqJs allows you to execute SQL-like queries on arrays.

var data = [
    {
        "_id": "5520f52e2c0a22541541bde1",
        "region": {
            "_id": "551e6779d8f1afa01bd86529",
            "name": "region_name"
        },
        "user": {
            "_id": "551a938af056a7fc099879c1",
            "firstName": "John",
            "lastName": "Boo",
            "username": "admin",
            "id": "551a938af056a7fc099879c1"
        },
        "__v": 0,
        "sport": [
            {
                "_id": "551e69c6d8f1afa01bd86533",
                "name": "Running"
            }
        ],
        "city": "some_city",
        "advert": "some_advert",
        "title": "I want to run!",
        "created": "2015-04-05T08:41:18.173Z"
    },
    {
        "_id": "552010740628cab002b3a700",
        "region": {
            "_id": "551e67b6d8f1afa01bd8652f",
            "name": "region_name"
        },
        "user": {
            "_id": "551a938af056a7fc099879c1",
            "firstName": "Bill",
            "lastName": "Foo",
            "username": "bill_foo",
            "id": "551a938af056a7fc099879c1"
        },
        "__v": 0,
        "sport": [
            {
                "_id": "551e5e01abb74a8423410b88",
                "nazev": "Hockey"
            }
        ],
        "city": "some_city",
        "advert": "some_advert",
        "title": "some_title",
        "created": "2015-04-04T16:25:24.733Z"
    }
];

var result = jinqJs()
                .from(data)
                .where(function(row){return row.user.username==='admin';})
                .select();

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

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

Having trouble displaying an array in React.JS

I am facing issues with combining two arrays to add a label and its description without it getting all mixed up. The JSON data is imported into a database as "db" and everything appears jumbled together. [![I have attached an image to help explain my iss ...

Dynamic SQL queries are creating a new layer of security

Currently, I am working on developing a sidebar search feature wherein users can select specific options by clicking them. These selected variables are then used to generate an SQL query. Here is the process in more detail: 1. The user chooses options ...

The VueJS dynamic grid view

Currently, I am working on a project in VueJS using vue cli 3. I am facing an issue with implementing MasonryJS into my Vue project. The challenge lies in grasping how to integrate this masonry layout into my Vue application. ; (function(window) { // J ...

What is the best way to upload this file in VueJS?

I've come across a file written in outdated syntax that I need to use in a VueJS Component. You can find the file here. For instance, consider these snippets from the file: var CCC = CCC || {}; CCC.STATIC = CCC.STATIC || {}; CCC.STATIC.TYPE = { & ...

Using C# to simulate a mousewheel event on an IWebElement in Selenium

Description: An intricate arrangement of HTML rectangles displayed on the screen, each with a unique HTML id attribute making them selectable by Selenium IWebDriver and C# code without any overlaps. Objective: My goal is to use Selenium and C# to programm ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

Executing JavaScript code externally on Electron's local server

During local development, I prefer to store all of my separate JS scripts in a different folder. However, the only way I have found to do this is by omitting the declaration of the meta statement. Unfortunately, this omission triggers a warning message. ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

Locate all span elements with a specific class using jQuery and conceal the parent divs further up in

I'm currently attempting to identify a specific span element with a particular class and then move up the DOM to find the closest div with another specified class in order to hide it. Is there something I might be overlooking? Any insights as to why ...

Check out the article on reading file uploads using jQuery or Javascript

I have a basic file upload field: <input type="file" id="signature" /> Here is the jQuery code I am using: $('#save').click(function() { var element = $('#signature'); if (element.files && element.file ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

What steps do I need to take to connect a chat feature using the QuickBlox SDK within a React

I am planning to develop a chat app using QuickBlox on react native platform. I'm not sure where to begin. I'm looking for a library that supports QuickBlox chat on react native, or if creating a bridge between ios/android and react native is the ...

Shift the sideways movement of the triangle symbol

I currently have a main menu in the header with links, accompanied by a moving triangle that changes position as the user hovers from one page to another. While I want to maintain the dynamic movement, I am seeking a smoother transition effect similar to w ...

Break down and extract the fully organized variable using a single expression

Is it possible to destructure a variable while still having access to the structured variable within the same function call? For instance, what can be used in place of ??? below to achieve the desired result (and what other changes might need to be made i ...

Instructions for retrieving a key value pair from a logger's response

I am currently using log4javascript.js to capture client-side log messages on the server-side. However, I am facing difficulty in extracting key-value pairs from the response obtained. THE RESPONSE IS DefaultRequestBody(Some(Map(data -> List([{"logge ...

What could be causing this getJSON call to return undefined?

On our internal server, we have a JSON service that returns a specific record structure as shown below: { "getLTCWithIDsResult": { "AIMSubmissionID": "", "BrokerName": "", "DateApplied": "/Date(1389302726241-0600)/", ...

Ways to ensure that res.redirect is only executed after the completion of the for() loop

I am encountering an issue with my post route: app.post("/respostaAprovChamado", function(req, res){ if(req.isAuthenticated()){ for(let i = 0; i < req.body.indiceAprov; i++){ Chamado.updateMany( {"_id": re ...

Sanity.io's selection of schema field types for efficient and convenient

Hey there, guys! I recently started using Sanity.io and I'm curious whether there's a way to enhance my code efficiency and reuse certain fields across different schemas. I had an idea that goes something like this: cars.ts: export default { ...

Conditions must fail for window.location to execute

<a href="www.google.com" class="social" id="social">Click here for Link one</a> <a href="www.cnn.com" class="social" id="social">Visit Link two now!</a> <a href="www.facebook.com" class="social" id="social">This is Link thre ...

Using the JSon structure to call upon a RESTful API

I need help with a WCF REST Service that calls a method to update data in a database. The method requires a parameter. For example, my method signature is void MarkMobileAppApplicationAsCancelled(string applicationId); I am attempting to call this servic ...