How to tally objects within an array of nested array objects based on a specific property using JavaScript

My dataset looks like this:

var data = [
  {
    items: [
      {
        id: 123
      },
      {
        id: 234
      },
      {
        id: 123
      }
    ]
  }, {
    items: [
      {
        id: 123
      },
      {
        id: 234
      }
    ]
  }
]

I am looking to count the objects deeply nested in arrays within all data based on the 'id' property. e.g.

data.countObject('id',123) //return 3.
My data has approximately xx,000 items, what is the best solution for this? Thank you for your assistance (apologies for any errors in my English).

Answer №1

To achieve this task, you can utilize the functions reduce and forEach. Within the reduce callback, you have access to the items array by referencing curr.items, where acc and curr serve as parameters for the callback function. Additionally, you can employ curr.items.forEach to iterate through each object within the items array.

var data = [{
  items: [{
      id: 123
    },
    {
      id: 234
    },
    {
      id: 123
    }
  ]
}, {
  items: [{
      id: 123
    },
    {
      id: 234
    }
  ]
}];

function getCount(id) {

  return data.reduce(function(acc, curr) {
    curr.items.forEach(function(item) {
      item.id === id ? acc += 1 : acc += 0;
    })
    return acc;
  }, 0)
}

console.log(getCount(123))

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

Guidelines for retrieving specific json information using PHP

Hello there, I am currently retrieving data directly from an API endpoint. While I was successful in obtaining the id, I am facing difficulty in accessing the "type":"participant" part, specifically the skillTier. Even though I have written the following ...

Is there a way for me to determine the location on disk from which a module is being loaded?

I am encountering a situation with a module @vendorname/functions that seems to be missing from the filesystem as per npm list $ npm ls @vendorname/functions <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76xxxxxxx20">[emai ...

Finding a way to extract a singular text node after the Span element but before the br tag using Selenium WebDriver

I am trying to retrieve the text between span and br tags. In the HTML snippet below, I am aiming to extract the Orange text: <td role="grid cell"> <span class="ui-column-title">Fruits</span> <span id="all fruits"> "Orange" < ...

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

Managing complex chains of asynchronous functions to produce a consolidated result

Running on my backend server with express, I have the following: app.post("/login", async(req, res) => { try { const { username, password } = req.body; let result = await checkCredentials(username, password) console.log("resu ...

Transform Tree Hierarchy into Two-Dimensional Array

Looking to transform a tree-like structure into a 2D array. Defined by the following person class: public class Person { public string Name { get; set; } public List<Person> Children { get; } = new List<Person>(); } With data populat ...

The functionality of Google Maps fails to operate within an Angular directive

Trying to implement the GoogleMapsAPI but facing issues with displaying the map in the directory template. Check out the following markup and code snippet: <gmap-locator></gmap-locator> . app.directive('gmapLocator', function () { ...

Unable to confirm the validity of the object within another object

To retrieve the values of the object, I use the following code snippet: const link = $("#link").val(); const state = $("#state").val(); etc... The Object is then constructed with these values: const departmentObject = { position, name, link, sta ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Steps to make the placeholder in an MUI TextField component move to the top of the box instead of staying within the border:

I'm working on styling a text field in MUI to achieve the look shown in the image below: https://i.sstatic.net/JHhpf.png However, my current implementation looks like this: https://i.sstatic.net/5N7hH.png Currently, when I click inside the text fi ...

Is there a way to eliminate the # sign from hash data using jQuery?

Can anyone help me retrieve the hash value from the URL? var hash = window.location.hash; I am looking for a way to remove the "#" sign from the hash. Any suggestions? ...

Generate a custom JSON structure by utilizing information stored within PHP variables

I am facing a challenge with formatting arrays in a specific JSON structure required by a third-party app. The desired JSON format is as follows: { "appData" : { "appKey" : "blah blah", "synth" : { "synth1" : { "mono" : ...

Attempting to access the server route does not involve the function str.CharAt

I seem to have encountered an issue while trying to deploy an API to Heroku. Initially, everything was running smoothly on my local machine, but at some point, I must have made a mistake, resulting in a broken setup. When I access the page using just local ...

Retrieve a specific column from a database based on its unique identifier using LINQ and WebMethod

I am currently working on a feature that involves populating a webform within a jQuery UI modal when a user clicks on an edit button. This data needs to come from a database using AJAX to call the method getProjectByID() and populate the webform in the mod ...

In angular, concealing the pagination bar can be achieved when the quantity of pages is lower than the items per page count. Let's delve into

I am facing an issue where I need to hide the pagination bar if the number of pages being rendered is less than the items per page. I attempted to use ng-show but it was not successful. <tr ng-repeat="row in allItems"> ...

Is there a way to implement jquery (or other external libraries) within Typescript?

Currently, I am diving into Typescript to enhance my skills and knowledge. For a project that is being served with Flask and edited in VSCode, I am looking to convert the existing JavaScript code to Typescript. The main reason for this switch is to leverag ...

Issue with two Jquery slider forms

Within a Jquery slider, I have implemented two distinct forms (using this specific Jquery slider: http://tympanus.net/Tutorials/FancySlidingForm/) . My goal now is to establish JavaScript/jQuery validation for these two forms separately BASED on the form ...

Expanding and collapsing Javascript accordion when a new tab is opened

Is there a way to prevent previously opened accordions from remaining open when opening another accordion? Any help on fixing this issue would be greatly appreciated. Thank you! let acc = document.getElementsByClassName('ac-btn'); let i; fo ...

Utilizing AngularJs to connect server-generated HTML content to an iframe

My Angular app functions as an HTML editor that transmits the template to a server for rendering with dynamic data. The rendered content is then sent back to the client, where it needs to be placed inside an iframe for preview purposes. It appears that ng- ...

What could be the reason my hex code generator is outputting variable names instead of their assigned values?

I am currently working on developing a unique hex code generator using random values. At the moment, my focus is on displaying six random values in the HTML. // The characters A-F and numbers 0-9 can be utilized var button = document.querySelector(&quo ...