What's the best way to extract the total number of arrays stored within an object?

I am working with a JSON webservice that has a specific format.

 { Name:['a','b'], Name:['cd','ef'], Age:{...}, Address:{...} }. 

Within this object, there are 2 arrays & 2 objects, though the number of arrays and objects can vary. I am looking for a way to specifically count only the number of arrays within the main object. While there may be other solutions to my issue, I specifically need my code to be implemented in a .JS (JavaScript) file.


Initially, I attempted:

Object.keys(mainobject).length; 

However, this approach provided me with a total count of both arrays and objects in the main object.

Answer №1

let info = { Name:['a','b'], OtherName:['cd','ef'], Age:{a: 12}, Address:{a: 'asdf'} }

let numOfArrays = Object.keys(info).filter(function(key) {
    return info[key] instanceof Array; //or Array.isArray(info[key]) if the array was created in another frame
}).length;

alert(numOfArrays);

Please note that this may not be supported in older versions of IE

Check out on jsFiddle

To ensure compatibility with browsers that do not support it, consider using shims from MDN:

Object.keys

Array.filter

Answer №2

I will create a function to tally up the different data types

var obj = {
    key1: ['a','b'], key2: ['cd','ef'],
    key3: 0, key4: 1,
    key5: {alpha:'beta'},
    key6: new Date(),
    key7: "bar"
};

function checkType(obj) {
    var type = Object.prototype.toString.call(obj).slice(8, -1);
    if (type === 'Object') return obj.constructor.name;
    return type;
}

function countDataTypes(obj) {
    var key, hasOwnProperty = Object.prototype.hasOwnProperty,
        result = {}, dataType;
    for (key in obj) if (hasOwnProperty.call(obj, key)) {
        dataType = checkType(obj[key]);
        if (!result[dataType]) result[dataType] = 1;
        else ++result[dataType];
    }
    return result;
}

var dataTypesCount = countDataTypes(obj);
// Object {Array: 2, Number: 2, Object: 1, Date: 1, String: 1}

If I am interested in knowing just the number of Arrays

var numOfArrays = dataTypesCount.Array || 0; // 2 Arrays in this scenario

Answer №3

To determine the type of each item within your object, you could iterate through each member.

var count = 0;
for (var foo in mainobject) {
    if (foo instanceof Array) count++;
}

After running this code, simply access the value stored in count.

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

Showcasing information from a database on an HTML page with the use of Node

I am currently attempting to fetch data from my database and display it on an HTML page in a table using EJS for rendering. I found inspiration for my code on this website: Although the database connection is successful, I am encountering difficulties wit ...

Problem: Vue 3 build does not generate service worker

After adding the "@vue/cli-plugin-pwa": "^4.5.12" to my package.json and setting up workbox configuration in my vue.config.js, I encountered an issue. When running npm run build:prd with the script vue-cli-service build --mode prod.exam ...

Surprising results when using react-router-dom alongside React's Context API

I am currently working on a small project where I am trying to implement basic authentication using the React Context API without Redux. Here is the code snippet: import { createContext, useContext, useState } from 'react' export const AuthConte ...

Is it not feasible to pass a local variable with the same name as a global variable in JavaScript?

const foo = "foobar"; function bar(){ const foo = foo || ""; return foo; } bar();` When running this code, it returns an empty string. Why is JavaScript unable to reassign a local variable with the same name as a global variable? Most other progra ...

Issue with Jquery animation persists: mouse cursor does not change and style remains unchanged even after clicking

I have encountered an issue with JQuery animation on Chrome. According to the requirements, I need to animate a div when a link is clicked. When the cursor hovers over the link, it should be underlined and change to a pointer. However, even after clickin ...

The Register Page is failing to load

I'm currently tackling a validation form project with NodeJS. However, I'm encountering an issue where register.ejs is refusing to render. Despite my attempts to tweak the paths and navigate through different folders, the problem persists. As a n ...

Struggling to make Bootstrap-vue form validation functional

I am encountering an issue with form validation in Vue CLI and Bootstrap. When the page loads, all input fields show as invalid due to being assigned the is-invalid class. I managed to solve this problem by setting the state prop to null when it is false. ...

Guide to retrieve the Last-Modified date using Javascript

It is common knowledge that the document.lastModified function returns a string containing the date and time when the current document was last modified. Is it possible to obtain the Last-Modified for a script? Here is an example of HTML code: ... <s ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Having trouble extracting information from JSON object array following an AJAX post?

My website transfers data through JSON objects using Angular's $http post. If you'd like to see the console logs and responses, visit my website: Initially, I used x-form-urlencoded encoding successfully and decided to switch to application/jso ...

Exploring the capabilities of referencing MongoDB documents with the populate method in Node.js

I have been working on referencing in Node.js using the populate method, but I am unsure about how exactly it works. In my code, I am creating a reference to the user collection from my child collection. I have two collections - one for children and anothe ...

Mastering Java - Chapter 25 - Dealing with Class Cast Exception when Using Generics with Lists and Arrays

Currently, I am engrossed in reading the second edition of Effective Java by Joshua Bloch, specifically item 25 on page 122. In this chapter, the author presents a code snippet which reads as follows: // Naive generic version of reduction - won't com ...

JavaScript guide: Deleting query string arrays from a URL

Currently facing an issue when trying to remove query string arrays from the URL. The URL in question looks like this - In Chrome, it appears as follows - Var url = "http://mywebsite.com/innovation?agenda%5B%5D=4995&agenda%5B%5D=4993#ideaResult"; ...

Is there a way to verify the continuity of a string array and, if it's not continuous, how can it be removed?

For my current project, I have a table structured like this: String[] s1={"22","Software","1"}; String[] s2={"45","Software","2"}; ..... List<String[]> myL=new ArrayList<String[]>(); myL.add(s1); myL.add(s2); .... The goal now is to filter ou ...

Is there a way to dynamically switch between AngularJS modules based on a configuration change?

Understanding the inner workings of Dependency Injection with AngularJS modules has sparked an idea in my mind. I thought about leveraging this concept to switch between different modules based on the environment of the application. For instance, I aim to ...

Encountering issues when trying to access a property after setting an EJS variable in

Whenever this code runs, an interesting type error occurs within the if statement. It says: Cannot read property product.thumbgallery1 of undefined. var urlArray= []; var product = '<%- product %>'; console.dir(product); ...

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

Guide for Injecting Personalized Information into Current Plist Array Information

I am currently working on inserting additional data into my propertylist array. This is the situation I am dealing with: I receive JSON data from the server and load it directly into a plist. I need to add custom keys and values with specific types to th ...