Calculate the number of arrays in an object and then substitute them

Currently, I have an object that is returning the following data:

Object {1: 0, 2: Array[2], 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}

My goal is to replace the "Array[2]" with just the number "2" (indicating how many records are in the array).

Answer №1

Below is the given code snippet

let obj = {1: 0, 2: [0, 1], 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0};

Object.keys(obj).forEach(function(key) {
    if (Array.isArray(obj[key])) {
        obj[key] = obj[key].length;
    }
});

Answer №2

Give this a shot:

Take a look at this snippet of code that utilizes the Object.keys method and forEach loop to iterate through your_object and check if each property value is an array. If it is, the code will update the property with its length.
Object.keys(your_object).forEach(function(key){
    if (toString.call(your_object[key]) === '[object Array]') {
        your_object[key] = your_object[key].length;
    }
});

Answer №3

If you want to standardize the lengths of all arrays, you can follow this method:

for( let index in object ) {

  if( object[index] instanceof Array ) {
    object[index] = object[index].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

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Steps for incorporating monaco-editor into a website without utilizing nodejs and electron

Currently, I am working on building a basic web editor and came across Monaco-editor. I noticed someone using it with Electron, but I am interested in integrating it into plain JavaScript just like on their webpage (link). However, I am struggling to fin ...

Enhancing the current Node.js, Express, MongoDB, and Socket.io stack with the integration of AngularJS

After spending some time developing a web app using Node.js, Express, MongoDB, Mongoose and Socket.io, I've successfully released version one. Looking ahead to version two, my plan is to revamp the UI completely and switch to a front-end framework lik ...

The state initialization process is beginning with an [object Object] being passed into the setState function

Within the async function provided below, I am invoking stationData to verify that an array of objects is being passed into bartData (which currently consists of an empty array). Upon exploration, I have observed a response containing the anticipated array ...

"Incorporating Adobe Edge Animate alongside AngularJS and AngularUI Router for dynamic web design

Currently, I'm in the process of integrating multiple animations created using Adobe Edge Animate into a single AngularJS application for a project. These animations will serve as the visual elements for a game, with player input controlling the compo ...

Executing Grunt: Setting up a dual Connect and Express server to operate on one port

I'm still fairly new to Grunt and I've been wondering if it's possible to run both servers on the same port simultaneously. I seem to be encountering some issues with this setup, most likely stemming from the Grunt file. I am utilizing grun ...

Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that ...

Containers shared among Next.js pages within a folder

Is it possible to have a shared container for all pages within a specific folder in NextJS? One potential solution could involve the following code: // pages/folder/index.js export default function Container({ children }) { return <Container>{ch ...

Establishing the default tab in JavaScript

Here's the JavaScript code snippet I have: jQuery(document).ready(function($) { // filtering subcategories var theFilter = $(".filter"); var containerFrame = $(theFilter).closest(".container-frame") var filterHeight = $(".filter").children("li") ...

Methods to acquire the 'this' type in TypeScript

class A { method : this = () => this; } My goal is for this to represent the current class when used as a return type, specifically a subclass of A. Therefore, the method should only return values of the same type as the class (not limited to just ...

Is there a way to set up a loop for managing four separate drop-down lists?

While the code is functioning properly, I am determined to streamline it into a loop. Unfortunately, all my attempts thus far have been unsuccessful. The code displays four drop-down lists with different Id's, but they share the same class name (optio ...

Using Ajax to update multiple text field rows with unique values

I have a question regarding utilizing Ajax to update the second text field based on the input from the first text field. I am looking to create multiple rows using a for loop, with each row having its own set of values. HTML <form style="text-align:c ...

Converting a variety of form fields containing dynamic values into floating point numbers

Trying to parse the input fields with a specific class has presented a challenge. Only the value of the first field is being parsed and copied to the other fields. https://i.stack.imgur.com/QE9mP.png <?php foreach($income as $inc): ?> <input ty ...

Using Typescript to implement an onclick function in a React JS component

In my React JS application, I am using the following code: <button onClick={tes} type="button">click</button> This is the tes function that I'm utilizing: const tes = (id: string) => { console.log(id) } When hovering ov ...

If viewed on a mobile device, separate the array (indexed list) into two rows

Currently, I am working on my Ionic project where I am trying to implement an indexed list horizontally instead of vertically. While the list looks good as it is now, I want to make sure it supports smaller screen devices too by splitting the list into two ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Is javascript or ajax the best choice for updating a database in asp.net mvc?

I need help with updating a row in my database based on a change event from a dropdown list. I am not sure whether to use javascript or ajax for this purpose as I want to avoid page refresh. Any recommendations on which method is best and where I can find ...

Having trouble with d3 / svg layering when introducing new nodes overtime

Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

What is preventing the control from being passed back from the PHP file to the AJAX success function?

My website is built using PHP, Javascript, and AJAX. Below is the essential code snippet: JS code (AJAX function): $("#btn_add_event").click(function(){ var strSeriaze = $( "#formAddEvent" ).serialize(); url = $( "#formAddEvent" ).attr('act ...

Using more than one submit button in an HTML form

I am attempting to include multiple buttons on a single form. I would like to perform different actions on the form depending on which submit button is clicked. <script type="text/javascript> $("#<portlet:namespace/>Form").submit(function( ...