What is the best way to tally the elements of a nested object within a group of objects?

I am working with an array of objects that contain nested arrays of objects, similar to what is shown in Code snippet 1. My goal is to calculate the number of records within the nested array where the parent_user_id matches the id. Based on this criteria, from Code snippet 1 the count should be 4, and the total count should include iterating through similar outer array of objects.

**Code Snippet 1**
[
{
    "name" : "A",
    "description" : null,
    "users" : [
        {
            "id" : "63a8808c52f40e1d48a3d1da",
            "owner" : "John Doe",
            "purchase_date" : "2022-12-25,
            "status" : "active",
            "parent_user_id" : "63a8808c52f40e1d48a3d1da",
            "recent_items": ["tomato",onion]
        },
        ...
    ]
}
]

I have attempted solutions involving loops and iteration, but I am wondering if there is a simpler way to accomplish this task using JavaScript or Typescript?

Answer №1

const data = [
    {
        "name" : "A",
        "description" : null,
        "users" : [
            {
                "id" : "63a8808c52f40e1d48a3d1da",
                "owner" : "John Doe",
                "purchase_date" : "2022-12-25",
                "status" : "active",
                "parent_user_id" : "63a8808c52f40e1d48a3d1da",
                "recent_items": ["tomato","onion"]
            },
            {
                "id" : "63a880a552f40e1d48a3d1dc",
                "owner" : "John Doe 1",
                "purchase_date" : "2022-12-25",
                "parent_user_id" : "63a8808c52f40e1d48a3d1da",
                "recent_items": ["onion"]
            },
            {
                "id" : "63a880f752f40e1d48assddd",
                "owner" : "John Doe 2",
                "purchase_date" : "2022-12-25",
                "parent_user_id" : "63a8808c52f40e1d48a3d1da",
            },
            {
                "id" : "63a880f752f40e1d48a3d207",
                "owner" : "John Doe 11",
                "dt" : "2022-12-25",
                "status" : "inactive",
                "parent_user_id" : "63a880f752f40e1d48a3d207",
            },
            {
                "id" : "63a880f752f40e1d48agfmmb",
                "owner" : "John Doe 112",
                "dt" : "2022-12-25",
                "status" : "active",
                "parent_user_id" : "63a880f752f40e1d48agfmmb",
                "recent_items": ["tomato"]
            },
            {
                "id" : "63a880f752f40e1d48agggg",
                "owner" : "John SS",
                "dt" : "2022-12-25",
                "status" : "inactive",
                "parent_user_id" : "63a880f752f40e1d48agggg",
            },
            {
                "id" : "63a880f752f40e1d487777",
                "owner" : "John SS",
                "dt" : "2022-12-25",
                "parent_user_id" : "63a880f752f40e1d48agggg",
            }
        ]
    }
    ]

const filteredData = data[0].users.filter((user, idx) => user.id === user.parent_user_id)
console.log(filteredData.length);

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

When triggering the fireEvent.mouseOver event, it seems that document.createRange is not a valid

Having trouble using fireClick.mouseOver(tab) to test tooltip functionality on tab hover. Here's a snippet of the code: it('should handle change on hover of tab', () => { const {getByTestId, getByRole} = renderComponent('Dra ...

iOS is currently experiencing issues with touch events not functioning properly within iFrames

Events like touchstart or touchend do not work when attached to the window inside an IFrame on iOS devices. Check out this straightforward example: mainpage.html <!DOCTYPE HTML> <html style="height: 100%;"> <head> <meta charset= ...

What is the method for assigning a class name to a child element within a parent element?

<custom-img class="decrease-item" img-src="images/minus-green.svg" @click="event => callDecreaseItem(event, itemId)" /> Here we have the code snippet where an image component is being referenced. <template&g ...

error encountered in ajax contact form due to issue with select element

I'm experiencing an issue with my ajax contact form, where the input field and select element are not providing the expected results. This is the HTML Form Code (with "name" as the input and "iphone" as the select element) <div id="contact_form" ...

Select the Month and Year from the Dropdown Menu

I'm attempting to manage the selection of "Month" and "Year" in a dropdown list. I have two fields, "Start Date" and "End Date". In the "Start Date" field, I am displaying the "Current Month" and "Year", for example, "March 2020". My goal is to restri ...

The sequence of HTML attributes

Could there be a subjective angle to this question (or maybe not)... I work on crafting web designs and applications using Visual Studio and typically Bootstrap. When I drag and drop a CSS file into an HTML document, the code generated by Visual Studio loo ...

Save the MySQL query results to a CSV file by exporting them with the f

I have been attempting to export the results of a SQL query to CSV using fputcsv, but I keep encountering the error "fputcsv() expects parameter 2 to be an array, string given". I tried following the solution provided on this page - Query mysql and export ...

Updating and deleting Firebase data from an HTML table: A guide

I am struggling to make the onClick function work in order to update and delete already retrieved data from an HTML table view. Despite trying different approaches, I can't seem to get it right. var rootRef = firebase.database().ref().child("prod ...

Is it necessary to clean up the string to ensure it is safe for URLs and filenames?

I am looking for a way to generate a URL-safe filename in JavaScript that matches the one created using PHP. Here is the code snippet I currently have in PHP: <?php $clean_name = strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕ ...

The parameter "disabled=false" is not functioning properly in TypeScript 2.1

Struggling to deactivate a field by accessing the element ID in TypeScript 2.1. Came across this syntax for TypeScript 1.5, but unfortunately, it doesn't seem to work in 2.1. Any assistance would be greatly appreciated. ( document.getElementById(&apo ...

Which child node of the html tag represents the "text"?

In my quest for answers, I have searched extensively but to no avail: As we all know, when a web page is loaded in a browser, it generates a tree-like structure called the Document Object Model (DOM). This allows Javascript to manipulate the elements of t ...

What methods are most effective for showcasing Flash messages within Express.js?

I have a Node.js app in the EJS framework and I am new to JavaScript. Could someone please advise me on the correct way to set flash messages in Node.js? Below is my code which is throwing an error: C:\Users\sad\Desktop\Node Applica ...

After updating to Chrome version 65, I noticed an unexpected error popping up: The onClick listener was expected to be a function, but instead, it

I recently encountered an error in my React app that has been causing some issues. https://reactjs.org/docs/error-decoder.html?invariant=94&args[]=onClick&args[]=string Minified React error #94: Expected onClick listener to be a function, instea ...

What is the method for testing the effectiveness of required input control without any modifications

One of my components has a template structured as follows: <form class="form-horizontal" #privateEmailForm="ngForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label class="col-md-4 control-label text-left" for="tiNewEmai ...

No values are present in the Character Constant Array, despite having been assigned [C++]

I'm encountering an issue with assigning a string value in a character constant array. Each time I assign a string value to a specific position of the character array, that position becomes initialized to an empty string after getting a new value in t ...

Choose Select2 to remove all selected options

I'm looking for a way to remove all selected values in one click without having to specify each individual 'id' separately. I've tried experimenting with different approaches, but so far, I've only been able to deselect the first ...

Setting a variable equal to user input

When using a jQuery script, the elements for the details are dynamically created inside a jQuery function. However, there seems to be an issue with assigning the value from the variable "startLocation" to the input "detail_startLocation[]". Only the firs ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

Issue with prop inheritance in componentInheritance problem with passing props to

How can I pass the state function setMyChoice as a prop to the GamePlay component in a rock paper scissors Nextjs application? The goal is to produce a value for comparison. In the Gameplay component, I then pass a prop to another component called PlayButt ...

What is the best way to convert a deeply nested PHP array/object into JSON format?

For those who want a shorter explanation, here it is: I have a JavaScript array filled with objects. Some properties of these objects contain arrays of objects, which in turn may have more arrays or objects nested within them. This results in 5 levels of n ...