What is the method to determine the size of an array of objects where each object contains its own internal array?

Here is the data that I have:

var a=[
        {
            name: "time",
            Details:[
                {value:"month",checked:true,id:1}
            ]
        },
        {
            name: "product",
            Details:[
                {value:"abc",checked:true,id:2},
                {value:"abx",checked:false,id:3}
            ]
        }
    ]

My goal is to efficiently find the count of checked items. In this example, the count is 2. Can someone suggest an optimized approach to achieve this without using a for loop or nested filters?

Answer №1

You should consider using standard reducers in this scenario.

const items=[
  {
    title: "time",
    details:[
    {value:"month",selected:true,id:1}
    ]
  },
  {
    title: "product",
    details:[
    {value:"abc",selected:true,id:2},
    {value:"abx",selected:false,id:3}
    ]
  }
]

const totalSelected = items.reduce((total, item) => total + item.details.reduce((all, detail) => all + (detail.selected === true ? 1 : 0), 0), 0)

console.log(totalSelected);

Here is the code snippet in a more organized manner:

const totalSelected = items.reduce((total, item) => {
  return total + item.details.reduce((innerTotal, detail) => {
    if (detail.selected) {
      return innerTotal + 1;
    } else {
      return innerTotal;
    }
  }, 0), 
 }, 0);  

Answer №2

To achieve the desired outcome, you must utilize two nested forEach() functions:

var items = [{
    name: "time",
    details: [{
      value: "month",
      checked: true,
      id: 1
    }]
  },
  {
    name: "product",
    details: [{
        value: "abc",
        checked: true,
        id: 2
      },
      {
        value: "abx",
        checked: false,
        id: 3
      }
    ]
  }
];

var count = 0;
items.forEach(({details}) => details.forEach(({checked}) => {
  if(checked){
    count++;
  }
}));


console.log(count);

Answer №3

Give this a try, I'm confident it will work for your issue

    let TotalCount=0;
var b=[
            {
                type: "color",
                Info:[
                    {name:"red",selected:true,id:1}
                ]
            },
            {
                type: "size",
                Info:[
                    {name:"medium",selected:true,id:2},
                    {name:"large",selected:false,id:3}
                ]
            }
        ];
b.map(function(item,key){
item.Info.map(function(subItem, subKey){
if( subItem.selected==true){
TotalCount++;
}
});
}); 

Answer №4

If you want to retrieve all details with a checked value, you can utilize a combination of different functions:

a.map(item => item.Details).flat().filter(item => item.checked)

Begin by mapping the items, then flatten the results into a single array, and finally filter based on the checked value.

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

Manage the jQuery resize handles by controlling their behavior when clicked inside and outside of the corresponding DIV

I am dynamically creating DIV elements and using jQuery resizeable handles on them. Is there a way to show the handles on click or hover, and then hide them when clicking outside the relevant div? Check out this jsFiddle $('.resizable').on(&ap ...

Having trouble with basic authorization for Facebook API using JavaScript?

I am having an issue with my source code. When I run it, I receive an alert that says "No Response" and then the Facebook page displays an error message stating "An error occurred with MYAPP. Please try again later" <div id="fb-root"></div> & ...

After updating my Ionic Android App to Angular 12, it got stuck on a blank white screen with an error message stating: "goog.getLocale is

After successfully upgrading my Ionic App with Angular 11 to version 12, everything seemed fine when running it in the browser. However, when attempting to launch it on an Android device, I encountered a white screen after the splash-screen vanished. My t ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

interactive symbols in a reorganizable tree structure

I have been developing a customizable tree list for our users to arrange their website content. It allows them to add and rearrange pages by dragging and dropping. Each list item includes the page name and three icons (lock, visible, and edit). The challe ...

Issue occurred: The error "Undefined offset 1" was encountered while trying to upload a file via

Every time I try to pass data into my file upload controller, I keep encountering an error message that says undefined offset: 1. function TestFileUpload() { $i=0; if(!isset($_FILES[$i]) ) { echo "No file is being uploaded"; } el ...

click event not triggering custom hook

I have developed a custom hook for fetching data and am struggling to implement it successfully. Below is my custom hook: import { useReducer } from "react"; import axios from "axios"; const dataFetchReducer = (state, action) => { ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Strengthening the core: Preserving a full set of data on a server that doesn't

After going through various discussions on how to save a Backbone collection using a non-RESTful server, I am still a bit puzzled. I have set up a collection where I've customized the data for posting to my API ("/api/entity/735/request/personDelete" ...

How can a PrivateRoute component effectively handle waiting for an asynchronous response?

I've encountered an issue with my PrivateRoute component that is supposed to verify the validity of a token. The problem lies in the fact that the validation process for rendering a view is not functioning as expected, always rendering: App.js const ...

The expandable column headers in Primeng are mysteriously missing

I'm facing an issue with my expandable row in Angular2 using Primeng2, where the column headers for the expandable columns are not displaying. Below is the code snippet of my table with expandable rows: <p-dataTable [value]="activetrucks" expanda ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Before proceeding to update in Angular 8, ensure the repository is not dirty. Commit or stash any changes that have been

Encountered an Issue The repository is not clean. Please commit or stash any changes before updating. When upgrading from version 7 to Angular 8, I faced this error. To find out more about the upgrade process, you can visit the Angular Guide for Upgra ...

Converting a JavaScript variable into PHP using ajax: A comprehensive guide

Can someone please help me troubleshoot this code for passing a JavaScript variable to PHP? It doesn't seem to be working properly. I want to extract the value of an ID from JavaScript and send it over to PHP. <!DOCTYPE html> <html> ...

Access your Angular 2 application on an external device during the development process

Is there a way to view your app in an external device like a cell phone web browser, instead of just running npm start and viewing it in your desktop browser? ...

How does the "deliver_order" function retrieve the value of the name parameter?

function take_order(name, callback1) { console.log("order has been taken."); callback1(name); } function prosess_order(name, callback2) { console.log(`prosesing order for ${name}.`); callback2(name); } function deliver_order(name) { console.log ...

Tips for implementing a switch-case statement with variable formats that may not always be

switch (req.path) { case "/api/posts": console.log("posts"); break; case "/api/posts/tags/*": // the part * is always changing depending on user input console.log("tags"); break; case "/api/best": console.log ...

Using TypeScript to Declare Third Party Modules in Quasar

I'm currently trying to integrate Dropzone-vue into my Quasar project. However, I've encountered an issue as I can't directly install and declare it in a main.js file due to the lack of one in Quasar's structure. Additionally, an error ...

Setting up a plan for executing Javascript server side scripts

Can JavaScript be executed server-side? If I attempt to access a script , can it be scheduled to run every four hours? Would most web hosts allow this, or is it considered poor webmaster practice? The main goal is to activate my website's webcrawler/ ...