"Calculating the size of JSON data up to a designated key

If we consider this as a variable created by utilizing .serializeArray()

 x={"acctType1":"individual","compare_act1":"contains","match_name_act1":"accountName","text_act1":"","acctType2":"individual","compare_act2":"contains","match_name_act2":"accountName","text_act2":"","transType1":"401kContribution","compare_trans1":"contains","match_name_trans1":"description","text_trans1":"","transType2":"401kContribution","compare_trans2":"contains","match_name_trans2":"description","text_trans2":""}

then the total length would be = 16.

by using :

Object.keys(x).length;

Suppose we only want to find the length up to transtype1, which should be 8 in this scenario - how can we achieve that?

Here's another case :

y={"acctType1":"individual","compare_act1":"contains","match_name_act1":"accountName","text_act1":"","acctType2":"individual","compare_act2":"contains","match_name_act2":"accountName","text_act2":"","acctType3":"individual","compare_act3":"contains","match_name_act3":"accountName","text_act3":"","acctType4":"individual","compare_act4":"contains","match_name_act4":"accountName","text_act4":"","acctType5":"individual","compare_act5":"contains","match_name_act5":"accountName","text_act5":"","transType1":"401kContribution","compare_trans1":"contains","match_name_trans1":"description","text_trans1":"","transType2":"401kContribution","compare_trans2":"contains","match_name_trans2":"description","text_trans2":"","transType3":"401kContribution","compare_trans3":"contains","match_name_trans3":"description","text_trans3":""}

the length of y = 32

however, the length up to transtype1 is 20

Many thanks in advance

Answer №1

Since objects lack inherent order, the properties within them do not correspond to a specific numerical position.

One approach could involve utilizing a for in loop and tracking until the desired item is located. However, there is no assurance that the outcome will align with the original sequence, the order from a prior iteration through the object, or any other specific arrangement.

Answer №2

According to @Quentin, relying on the order of keys when looping through an object using for-in may not be accurate. It's advisable to consider alternative ways of storing your data. However, if you still wish to proceed with this approach, here is a possible solution:

function calculateLength(obj,key){
    var count=0;
    for(var i in obj){
        if(i==key) return count;
        count++
    }
    return -1;
}
console.log(calculateLength(data,"category1"))//15
console.log(calculateLength(data,"nonExistingKey"))//-1

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

When passing a numeric value like 1 or 2 to the function in ajax, it functions correctly. However, when attempting to parse a variable, it does

I am facing an issue with my AJAX function. It works perfectly fine when I pass a number as a parameter, but not when I pass a variable. function display_message(userID) { $.ajax({ url: "displaychat.php", method: "post", data: { toui ...

toggle classes using jQuery when a link is clicked

I'm currently working on a jQuery function that will apply a class to a selected link (which opens a page in an iframe) and then remove that class when another link is chosen. Previously, I received assistance from another member for a similar task in ...

React's reset button fails to clear user inputs

Within my App, I have a straightforward form. I recently discovered that using a button with the attribute type="reset" should clear all input fields, but for some reason it's not working properly in React. Is there something crucial I am ov ...

How can you swap out a forward slash in vue.js?

I am facing a coding issue that I need help with: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the numbers in my item.id contain slashes, leadin ...

The Material UI appbar fails to resize properly on mobile devices

I have added a material-ui appbar to the top of my website. Check it out here: Website Appbar However, when I resize the website to mobile size, the appbar does not adjust responsively to the screen. Here's how it looks on mobile: Appbar when in mobi ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Submitting a form automatically in React Native using Redux

Is there a way to automatically submit a Redux Form in React Native based on certain conditions being met? I attempted to do so below, but it resulted in a warning. The documentation provides an example for remote submitting, but it uses HTML form's ...

Optimizing AngularJS ui-router to maintain state in the background

Currently working on an AngularJS project that involves a state loading a view containing a flash object. I am looking for a way to ensure that the flash object remains loaded in the background during state changes, preventing it from having to reload ev ...

Extracting <p> elements from a separate HTML file and cycling through them

I successfully created a website using only HTML, JavaScript, and jQuery without any server-side scripting or language. Within my website, I have a simple stream.html page that remains unstyled with no CSS formatting. <html> <head> </head& ...

How can I update and edit the State in React when using a bootstrap modal?

I am currently working on a project listing table and facing an issue. How can I prefill input fields in a Modal with the clicked data, edit them, and update the state with the new information provided? Below is a breakdown of my code in different files: ...

The schema encountered an error due to the absence of the save method

My current goal is to allow a logged in user to visit any user's URL and follow them. However, I'm encountering an issue: TypeError: Object { _id: 54bd6b90b7d4cc8c10b40cbd, name: 'Johnny', username: 'batman', __v: 0, ...

Reveal or conceal elements with a touch of animation

I am in the process of building my own website and I've been working on implementing a button that can toggle the visibility of a specific div element. While the functionality is there, I really want to incorporate an animation to enhance it. I attem ...

``I'm having trouble invoking a separate method within [displayWith] in Angular Material's autocomplete feature

Converting an address object into a string format for displaying the complete address in autocomplete is what I am trying to achieve. Below is the code snippet: address.component.html <mat-form-field class="address-autocomplete"> <input type=" ...

JQuery draggable and JavaScript functionality become disabled following an AJAX request

I have a click event declared as follows: $('body').on('click', 'input#searchVariables', function () { var datasetId = $('.TSDatasetID').val(); var term = $('#searchTextbox').val(); ...

Transfer an image file to a Ruby on Rails server

I am having trouble sending JSON data with an image included. When I send the request without the image as a Bitmap, everything works fine. But when I include the image in the JSON, the server returns an error. This is how I am sending the request: R ...

What steps should be followed to properly validate an unsubmitted form in Angular?

To ensure that the user submits the form before navigating to another page, I want to implement a feature where an error dialog pops up if the user types in the form but hasn't submitted it yet and tries to click a link to go to a different page. How ...

Challenges with JavaScript Object and Async forEach Loop - issues in assigning values

My intention is to create an object called 'tallys' that contains a key for each user in a game. The value assigned to these user keys is an array representing the weekly dollar values won in the game. Initially, I allocate each user in the game ...

Looking to loop through a JSON file in PHP in order to input its contents into a table. Need assistance with iterating through each subarray. Any help would be greatly appreciated

Trying to traverse JSON arrays to extract data and upload it to a SQL server has been my recent challenge. After scouring through numerous articles online, I managed to recursively print out the data but got stuck on how to store the values in a variable ...

How to give focus to a div in IE 8 after pressing the tab key, no jQuery required

We are facing a challenge with our datagrid where we have implemented navigation using the tab key. In IE 7 & 8, pressing the tab key shifts the focus away from the grid to the next element on the page. While in other browsers, we were able to prevent thi ...

Having difficulty with mapping data while trying to create a Todo list in ReactJS using a mapping component. (Note: Type annotations can only be used in TypeScript files)

Having recently started learning ReactJS, I decided to create a todo list using different methods. However, I am currently facing difficulties in mapping components, as my const Tododata is generating numerous errors. You can view the snippet at this link ...