Issue with JSON object key saving due to array length and element inconsistency

I am dealing with an API that returns a JSON Array of objects in the following format:

[
   {
     person_id:"12212",
     person_name:"some name",
     deptt : "dept-1"
   },
   { 
     person_id: "12211",
     person_name: "some name 2"
     deptt : "dept-2"
    },

]

My issue is related to saving the person_id values into an array. For some reason, I am not able to save them correctly and thus the length of the array is showing incorrect.

Using Chakram for this task, this is my current approach:

it('gets person id in array',()=>{
  let array_ids =[];
  let count=0;
    return response.then((api_response)=>{
     for(var i=1;i<api_response.body.length;i++){
       //this is correctly printing the person id of response
       console.log('Person ids are ==>'+api_response.body[i].person_id);
       count++;

       //this is not working
       array_ids = api_response.body[i].person_id;
}
      console.log('Count is '+count) //prints correct number
      console.log('Array length '+array_ids.length) //prints incorrect length - sometimes 11, sometimes 12
});
});

I am puzzled as to why this discrepancy is happening. Could it be due to this line?

array_ids = api_response.body[i].person_id 

Is this the wrong way of accessing elements in an array?

Answer №1

If you try this code snippet, you'll notice a crucial correction that needs to be made in your existing code. Instead of pushing IDs into an array, you are repeatedly assigning new values to the ID variable.

it('retrieves person IDs and stores them in an array',()=>{
  let array_ids = [];
  let count = 0;
    return response.then((api_response)=>{
     for(var i=1;i<api_response.body.length;i++){
       //this correctly displays the person id from the response
       console.log('Person ids are ==>'+api_response.body[i].person_id);
       count++;

       //the mistaken part is right here
       array_ids.push(api_response.body[i].person_id); // Correction needed
}
      console.log('Count is '+count) //displays correct count
      console.log('Array length '+array_ids.length) //unfortunately shows inaccurate length - sometimes 11, sometimes 12
});
});

Answer №2

Make sure to add the identifiers to an array

idsArray.push(api_response.body[i].person_id);

Utilize the Array.prototype.map() method

let idsArray = api_response.body.map(obj => obj.person_id);
let total = idsArray.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

Drop items next to the specified keys. Vanilla JavaScript

I am trying to create a new array of objects without the gender field. Can you identify any mistakes in my code? let dataSets = [ { name: "Tim", gender: "male", age: 20 }, { name: "Sue", gender: "female", age: 25 }, { name: "Sam", gender: "m ...

Ways to retrieve the latest message from a particular discord channel

Struggling to retrieve the latest message from one channel by sending a command in another channel. I envision the process to be like this: Channel 1: (I enter) "Get last message of channel 2" Channel 2: Last message is ("Hello"); Channel 1: I receive th ...

Retrieve a specific row from a table in Bootstrap

Is there a way to highlight a row in a table by clicking on it using CSS classes? $("#infoTable tr").click(function() { var selected = $(this).hasClass("highlight"); $("#infoTable tr").removeClass("highlight"); if (!selected) $(this).addClass( ...

There seems to be an issue with displaying the meta information in a Nuxtjs project using this.$

I am facing an issue with meta information in a Vue page. When I try to access "this.$route.meta", it does not display any meta information. However, when I inspect the Vue page element, I can see that there is indeed meta information present. How can I ...

Is it necessary to HTML encode the response of my Web API?

In the process of designing a new Web API that returns JSON as the content-type, I am facing a dilemma regarding certain characters such as ', ", <, and > which are valid within JSON formatting. The question is whether I should encode these char ...

Error with setting innerHTML property of a null nested div

This issue arises when the element is referenced before the DOM has completely loaded. To combat this, I have ensured that the necessary script runs only after the window has finished loading. Interestingly, if the getElementById() call is for a standalon ...

Conceal one object when the other is revealed?

Is there a way to hide the element with the class .close-button while showing another element with the ID #loading-animation? Can jQuery conditionals help achieve this? For example: if ($('#loading-animation').is(':visible')) { $ ...

Unexpected issue with Typo3 v9 - receiving empty Ajax Plugin JSON response

Consider the following setup in TYPO3 for an ajax request: ajaxAutocomplte_page = PAGE ajaxAutocomplte_page { typeNum = 111871 10 = COA_INT 10 { userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run extensionNa ...

Compendium and Collection

Hey there, I'm relatively new to Node.js and have encountered an issue with dictionaries and arrays. What I'm trying to achieve is accessing courseid and coursename. data = [ { name: "Ole Nordmann", pin: 1331, Job: ...

How can I use C# controller code to compare arrays within an array in a JSON file?

I've been working on aligning my model code with the structure of a json file. The json file contains a jsonArray called ReportList, which is functioning properly. However, I encountered an issue with the accountlist array nested within the items arra ...

Comparing elements in one array to elements in another array

In AngularJS, the $scope.categories array is populated from a multi-select element. $scope.categories = ["Adventure", "Strategy"] To compare this array with the categories in the items array below: $scope.items = [ { title: "Star Wars", ...

Utilizing Angular JavaScript for detecting and setting up JDK installations

I am working on an application that requires the installation of Java JDK. Therefore, I need to develop a detection function for JDK in the system. If it is not found, I plan to install it using a setup provided by me and also set it in the system variabl ...

Errors slipping through the cracks of Express middleware

When it comes to using express and typescript, I am attempting to create a middleware for error handling similar to Sentry. Below is the code snippet: const catchError = ( error: Error, req: Request, _res: Response, next: any ) => { console. ...

Transfer all classes to a different class using jQuery

I want to create a JavaScript/jQuery code that will do the following: // if (@media (max width: 480px)) { move all elements with classes `footer--column column--menu block` to the class `footer--columns block-group` and remove the `st--footer-column` ...

top method for serializing json on android

I recently ventured into android development and I'm currently working on an app where I chose to use retrofit for network requests. As I delved deeper, I discovered various response handling libraries like gson, jackson, moshi, among others. However, ...

There is a lack of output coming from jasmine-node

Looking to expand my knowledge in JavaScript, Node.js, and jasmine, I recently started working on a test from "The Node Craftsman Book" called FilesizeWatcher. After setting up the package.json file and running "npm install" to add jasmine-node locally to ...

In my experience, I have encountered issues with certain routes not functioning properly within Express

I am currently working on developing a tic-tac-toe game and looking to store user data in a database. However, I am facing an issue with the router I intended to use for this purpose as it is returning an 'Internal server error message (500)'. B ...

Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly. <% include ../partials/header %> <div class="jumbotron jumbotron-fluid"> <div class="container"> ...

AngularJS $resource sends the id as a query parameter rather than including it in the URL

I'm trying to retrieve data from a rest API by using the product id as part of the URL, rather than as a query parameter. Here is the factory code: .factory('Products', ['$resource', function($resource) { return $reso ...

The functionality of onclick is not fully compatible with Bootstrap

I attempted to utilize the onclick event with Bootstrap radio buttons in order to retrieve names and attributes, however, it did not work as expected. Some of the radio buttons triggered the event but were unable to fetch the name or class displaying as " ...