Exploring and retrieving JSON objects in multidimensional arrays

I'm facing a challenge with the code snippet provided below.

var employees = [
    {
    firstName: "John",
    lastName :"Doe",
      qualification: {Diploma: 'IT Software' , Degree: 'Software Engineering'}
    }, 
    {
    firstName:"Anna",
    lastName:"Smith",
      qualification: {Diploma: 'Business Accountant' , Degree: 'Business Administration'}
    }
];

for(var i in employees)
  {
    console.log(employees[i]);

  }

The current output of the above code is as follows:

[object Object] {
  firstName: "John",
  lastName: "Doe",
  qualification: [object Object] {
    Degree: "Software Engineering",
    Diploma: "IT Software"
  }
}
[object Object] {
  firstName: "Anna",
  lastName: "Smith",
  qualification: [object Object] {
    Degree: "Business Administration",
    Diploma: "Business Accountant"
  }
}

My goal is to customize the output so that instead of displaying [object object], it shows [index: 1] and [index : 2] for the respective objects.

Your assistance in solving this issue would be greatly appreciated. Thank you!

Answer №1

While iterating through the array using a for loop, you can retrieve the index using the variable i

for(var i in employees)
    console.log("index:"+ i);

Answer №2

Avoid using the for-in method to iterate through arrays without safeguards (more details and alternatives can be found in this answer), as it is not intended for that purpose.

If you need both the object and its index in the array, your best option is to use forEach:

employees.forEach(function(employee, i) {
    console.log("[index: " + (i + 1) + "]");
    // If you require access to the actual employee object, it can be retrieved using `employee`
});

Take note of the i + 1: In JavaScript (and programming in general), indexes typically start at 0, so adding one to the index will give you the desired output.

Alternatively, you can use a traditional for loop:

for(var i = 0; i < employees.length; ++i)
{
    console.log("[index: " + (i + 1) + "]");
    // Accessing the actual employee object can be done using `employees[i]`
}

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

Problems with Angular UI Router: Functions not functioning properly within the template

Currently, I am delving into the realm of Angular UI Router in order to effectively manage different sections of my application. If you'd like, check out this plunkr (http://plnkr.co/edit/KH7lgNOG7iCAEDS2D3C1?p=preview) Here are some issues that I&a ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Pick a selection from a different input

Consider the following two rows: <tr> <td class="contenu"><input type="text" name="numart" id="numart"/></td> <td class="contenu"><input type="text" name="descart" id="descart"/></td> <td class="contenu"& ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

Tips for incorporating PHP variables into Javascript code

Working with JavaScript: var counter = 1; var limit = 5; function addInput(divName){ if (counter == limit) { alert("You have reached the limit of adding " + counter + " inputs"); } else { var newdiv = document.createEle ...

Can you tell if an array consists solely of empty objects in JavaScript?

When working with a list of objects, I often find myself wondering how to determine if the elements in the list are empty. It seems like it should be simple, but sometimes it can get confusing. For example, in my react function component: console.log(list[ ...

Extract numerical values from a specific area and manipulate them

I'm facing an issue with a field that receives its input from a list of links associated with numbers, similar to a calculator but without operators. My goal is to retrieve these numbers and divide them by 12 using a function (converting from feet to ...

What is the best method to trigger a bootstrap modal window from a separate component in Angular 8?

I have successfully implemented a bootstrap modal window that opens on a button click. However, I am now facing difficulty in opening the same modal window from a different component. Below is the code I have tried: <section> <button type=&quo ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

Implementing Axios Get request to an Express backend

I'm new to the back-end development world, currently focusing on learning Front-End but I've decided to venture into creating my own server using Node.js. I have successfully installed Express, Cors, and Axios. It appears to be functioning as I c ...

Using a directive to implement Angular Drag and Drop functionality between two tables with 1000 records

My code is functional, but there seems to be a delay in the appearance of the helper(clone) when dragging starts. I have two tables - one for the include list and another for the exclude list. Users can drag table rows from the include table to the exclud ...

basic handler in expressjs using the PUT method along with jQuery ajax

I am currently developing a web application utilizing a REST API for server communication. The backend is built with Node.js using Express.js. One issue I am running into is the inability to read the request body in PUT requests. Below is my client-side co ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...

Using Web SQL always seems to throw me for a loop

I attempted to populate a web SQL database with some data, but encountered an issue. Here is my code: database(); for(var i=0; i<m.length; i++){ showid = m[i].id; showtitle = m[i].title; insert(); } function database(){ //open the database ...

jQuery's event delegation feature fails to work in conjunction with AJAX requests

I'm currently facing issues with jQuery's on event delegation: Below is the code snippet I am working with: HTML portion: <body> <!-- Page Content Wrapper--> <div id="sb-site"> <div id="overlay">& ...

How can you navigate a self-referencing one-to-many table in Sequelize to find the parent, the parent of the parent, the parent of the parent of the parent, and

I have a model called DriveObject, which has a self-referencing foreign key named parentId For the backend, I am utilizing express and node.js In my code, I have defined the association as follows: driveObject.hasMany(driveObject, { as: 'Children&ap ...

Generate an image of a "button" with dynamic hover text

I am trying to create a clickable image with dynamically changing text overlaid on it. I have the PHP code that retrieves the necessary information for the text, but I am struggling to create the button as I am new to this type of task. Here is an example ...

Utilizing Redux-Form to Retrieve Input Values

When a radio button is clicked, I want to display a form using redux-form. I tried following a tutorial that uses checkboxes but couldn't figure out how to implement it with radio buttons. The tutorial link is selectingformvalues. I have 2 radio butt ...

Using Angular 2 to Invoke Functions in Different Components

In my code, I am attempting to invoke a function from another component within a component. Here is an excerpt of my constructor logic: constructor( private http: Http, private appComponent: AppComponent ) { this.setUrl(); } setUrl() { i ...

I'm having trouble sending a string to a WCF service using jQuery AJAX. What's preventing me from sending strings of numbers?

Something strange is happening with my web service when using jquery ajax - I can only pass strings containing numbers. This was never an issue before as I would always just pass IDs to my wcf service. But now that I'm trying something more complex, I ...