Determine the dimensions of the objects within a JSON array

My JSON response creation looks like this :

{
  "G5LDUHRPEEA6B-39CFBWYA": [],
  "JMSK0DKOEEA0UXMY750O3W": [],
  "ISVN8JF1EEAD3W398ZNOSA": [
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": LA,
      "hello": "OUTSIDE"

    },
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": Chicago,
      "hello": “Inside"
    },
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": Austin,
      "hello": “Inside"
    }
  ],
  "VRG0IJF1EEAD3W398ZNOSA": [{

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": Chicago,
      "hello": “Inside"
    },
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": Austin,
      "hello": “Inside"
    }],
  "OGAESJF2EEAD3W398ZNOSA": [],
  "SC9OMJF2EEAD3W398ZNOSA": []
  }

I am in need of counting the total number of items within the arrays, even if they have internal arrays. I want to exclude empty internal arrays such as "SC9OMJF2EEAD3W398ZNOSA": []. I attempted _.size(collection) but require assistance on how to eliminate empty internal arrays. Appreciate your help in advance.

Answer №1

To calculate the total length of arrays, you can utilize the Array.prototype.reduce method along with looping through each array - check out the example below:

var object={"G5LDUHRPEEA6B-39CFBWYA":[],"JMSK0DKOEEA0UXMY750O3W":[],"ISVN8JF1EEAD3W398ZNOSA":[{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"LA","hello":"OUTSIDE"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Chicago","hello":"Inside"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Austin","hello":"Inside"}],"VRG0IJF1EEAD3W398ZNOSA":[{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Chicago","hello":"Inside"},{"delloData":"1478644629","ref":"75","dataType":"String","somePart":"Austin","hello":"Inside"}],"OGAESJF2EEAD3W398ZNOSA":[],"SC9OMJF2EEAD3W398ZNOSA":[]}

var result = Object.keys(object).reduce(function(previousValue, currentValue){
  previousValue += object[currentValue].length;
  return previousValue;
}, 0);

console.log(result);

Answer №2

If you ever find yourself needing to count all the elements in arrays, consider using lodash:

var obj = {
  "G5LDUHRPEEA6B-39CFBWYA": [],
  "JMSK0DKOEEA0UXMY750O3W": [],
  "ISVN8JF1EEAD3W398ZNOSA": [
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": "LA",
      "hello": "OUTSIDE"

    },
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": "Chicago",
      "hello": "Inside"
    },
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": "Austin",
      "hello": "Inside"
    }
  ],
  "VRG0IJF1EEAD3W398ZNOSA": [{

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": "Chicago",
      "hello": "Inside"
    },
    {

      "delloData": "1478644629",
      "ref": "75",
      "dataType": "String",
      "somePart": "Austin",
      "hello": "Inside"
    }],
  "OGAESJF2EEAD3W398ZNOSA": [],
  "SC9OMJF2EEAD3W398ZNOSA": []
  }

var result = _.flatMap(_.values(obj)).length

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.js"></script>

Answer №3

Utilizing lodash library:

<pre><code>
function getObjectLength(obj) {
  return _(obj)
    .values() // extract sub arrays
    .map('length') // map their lengths
    .sum(); // calculate the total length
}

var obj = {
  "G5LDUHRPEEA6B-39CFBWYA": [],
  "JMSK0DKOEEA0UXMY750O3W": [],
  "ISVN8JF1EEAD3W398ZNOSA": [{

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "LA",
    "hello": "OUTSIDE"

  }, {

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Chicago",
    "hello": "Inside"
  }, {

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Austin",
    "hello": "Inside"
  }],
  "VRG0IJF1EEAD3W398ZNOSA": [{

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Chicago",
    "hello": "Inside"
  }, {

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Austin",
    "hello": "Inside"
  }],
  "OGAESJF2EEAD3W398ZNOSA": [],
  "SC9OMJF2EEAD3W398ZNOSA": []
};

console.log(getObjectLength(obj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Alternatively, using ES6 and Object.values(), you can access all sub arrays, then spread and concatenate them. However, be cautious with large objects as this operation may be resource-intensive. Consider either the lodash approach or a simple Array#reduce:

<pre><code>
const getObjectLength = (obj) => [].concat(...Object.values(obj)).length;

var obj = {
  "G5LDUHRPEEA6B-39CFBWYA": [],
  "JMSK0DKOEEA0UXMY750O3W": [],
  "ISVN8JF1EEAD3W398ZNOSA": [{

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "LA",
    "hello": "OUTSIDE"

  }, {

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Chicago",
    "hello": "Inside"
  }, {

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Austin",
    "hello": "Inside"
  }],
  "VRG0IJF1EEAD3W398ZNOSA": [{

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Chicago",
    "hello": "Inside"
  }, {

    "delloData": "1478644629",
    "ref": "75",
    "dataType": "String",
    "somePart": "Austin",
    "hello": "Inside"
  }],
  "OGAESJF2EEAD3W398ZNOSA": [],
  "SC9OMJF2EEAD3W398ZNOSA": []
};

console.log(getObjectLength(obj));

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

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Looking to organize data based on duplicate values within an array using Javascript in the Vue framework

Can anyone provide assistance? Data = [{"name":A,"val":20}, {"name":B,"val":7}, {"name":C,"val":20}, {"name":D,"val":8}, {"name":E,"val":5}] SortedValue ...

Synchronizing multiple file changes simultaneously in Node.js

I have a small development server set up specifically for writing missing translations into files. app.post('/locales/add/:language/:namespace', async (req, res) => { const { language, namespace } = req.params // Utilizing fs.promises l ...

Arranging an array of JSON objects without keys in a specific order

Here is an array containing multiple objects without any keys: const result = [ ["Joe", "1", "2.22%", "$3,000.00"], ["Tom", "1", "2.22%", "$4,650.00"], ["Ryan", "4", "4.44%", "$18,925.00"], ["Jordan", "2", "4.44%", "$3,300.00"], ["Fred", "0" ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Implementing the map function in ReactJS to showcase data on the user interface

I seem to be facing an issue while attempting to utilize an array of data to display a <ul> element. Despite the console.log's working correctly in the code provided below, the list items fail to show up. <ul className="comments"&g ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

Remove a JSON object that corresponds to a particular value

I am in need of modifying a JSON file in a specific way. My goal is to remove an entire object from the file based on a certain condition. In this case, the condition is that "name": "value1_1:value1_2" The value of value1_1 is what I am targeting for ...

What is the best way to utilize AJAX for uploading .mp4, .mp3, and .doc files together with additional FormData?

Hello everyone, I have been successfully uploading files (documents and images) using AJAX. However, I am facing some challenges when it comes to uploading videos through AJAX. I have searched extensively on this site for solutions but have not found exact ...

Is it possible to execute a specified quantity of Promises simultaneously in Nodejs?

Currently, I am working on developing a web scraping application that utilizes a REST API to gather information from multiple entities on the server. The core functionality of this application can be summarized as follows: let buffer = [] for(entity in ent ...

"Although there are no errors, the ng-switch directive within the ng-repeat is not functioning as

I'm working on setting up a simple image gallery where I can dynamically change the displayed image by setting a specific number for currentImage. Check out my HTML code: <div class="main_image" ng-switch on="current_image"> <img ng-rep ...

Having difficulty updating the state with editorState retrieved from the server in ReactJs when using draftJs

Incorporating a rich text editor into React using draftJs has been successful. The editorState data is converted to raw data, stringified, and sent to the server for rendering on the front end. However, I am facing challenges in updating the editorState ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

Tips on implementing a script injected through the JS console to update form data in an Angular webpage and ensure that the changes are successfully saved

I am currently working on enhancing an existing electron app integrated with Angular. The main goal is to inject a script once the application is loaded in order to add a hotkey for efficiency. This hotkey should automatically click an edit button, input s ...

The argument in question has not been defined

Experimenting with AngularJS, I encountered an error message in the browser console when trying to display a particular example: Error: Argument 'mainController as mainCtrl' is not a function, got undefined at Error (native) at bb My pr ...

Spring MVC is set to generate JSON data but ends up displaying a web page instead

I have a method in my controller that produces a JSON payload using Spring MVC. @RequestMapping(value = "/MerchantMonitoringAPI", method = RequestMethod.GET,produces = "application/json") public String MerchantMonitoring() { ApplicationContext c ...

Is it not recommended to trigger the 'focusout' event before the anchor element triggers the 'click' event?

In a unique scenario, I've encountered an issue where an anchor triggers the 'click' event before the input field, causing it to lose focus and fire the 'focusout' event. Specifically, when writing something in the input field and ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

Issues encounteted when trying to implement Auth0/Angular2-Jwt in Angular 5 environment

There is a specific function in Angular2-JWT that I am trying to use to Show/Hide links based on the logged user token stored in localStorage. The function is called tokenNotExpired(). I have been exploring different approaches to implement conditional s ...