A guide on extracting JSON data from nested arrays using JavaScript

I have an array with nested objects that looks like this. How can I loop through the array and retrieve all the values of the "name" key?

Even though I've tried, I haven't been able to get the expected result.

dangle=  [[{name:"jack",age:"20"}],
         [{name:"ram",age:"25"}], 
         [{name:"vishy",age:"45"}]]

My desired output is "jack", "ram", "vishy". However, I'm currently getting the values from the first index like "jack", "20". Below is the code I've attempted so far. Any suggestions on how to achieve the correct output would be greatly appreciated. Thank you!

Here is my current code:

for(i=0;i<dangle.length;i++)
{
   alert(dangle[i]);
}

Answer №1

One effective method to iterate through an array is by utilizing a for loop. There are various ways to structure a for loop:

  • Utilizing a standard for loop (iterating through numbers where i represents each number):

    for(let i = 0; i < dangle.length; i++) { // iterating through the dangle array
      let arr = dangle[i]; // accessing each inner array at index `i`
      for(let j = 0; j < arr.length; j++) { // iterating through the inner array
        console.log(arr[j].name); // displaying the name of each object
      }
    }
    

let dangle =  [[{name:"jack",age:"20"}], [{name:"ram",age:"25"}],[{name:"vishy",age:"45"}]];
        
for (let i = 0; i < dangle.length; i++) {
  let arr = dangle[i];
  for (let j = 0; j < arr.length; j++) {
    console.log(arr[j].name);
  }
}

  • Using a for of loop (looping through the array elements, with arr representing each element):

    for(let arr of dangle) { // accessing each inner array in dangle (current inner array referenced as arr)
      for(let obj of arr) { // iterating through the contents in the current inner array, obj represents the content
        console.log(obj.name); // displaying the name of the content
      }
    }
    

let dangle =  [[{name:"jack",age:"20"}],[{name:"ram",age:"25"}],[{name:"vishy",age:"45"}]];
         
for(let arr of dangle) {
  for(let obj of arr) {
    console.log(obj.name);
  }
}

  • Using the .forEach higher-order function (iterating through array elements, with arr representing each element in the array)

    dangle.forEach(arr => arr.forEach(obj => {
      console.log(obj.name);
    }));
    

let dangle =  [[{name:"jack",age:"20"}],[{name:"ram",age:"25"}], [{name:"vishy",age:"45"}]];         

dangle.forEach(arr => arr.forEach(obj => { // looping through the outer array to access each inner array, and then through each inner array
  console.log(obj.name); // displaying the objects' names retrieved from the inner arrays
}));

Please Note: The examples above include 2 loops. This is due to the presence of a 2-dimensional array (array within another array). The outer loop is utilized to access each inner array, while the inner loop iterates through the elements (objects here) within each inner array. In scenarios where there is only one object in each inner array, the inner loop can be omitted and you can directly access the `0th` index of each inner array. However, to ensure scalability and ease of maintenance, the inner loop is included so that it remains functional even if there are multiple objects present.

You can use any of these for loops to populate an empty array with the names:

let names = [];
for(let arr of dangle) {
  for(let obj of arr) {
    names.push(obj.name); // adding the name to the names array
  }
}

console.log(names);

let dangle=  [[{name:"jack",age:"20"}], [{name:"ram",age:"25"}], [{name:"vishy",age:"45"}]]

let names = [];
for(let arr of dangle) {
  for(let obj of arr) {
    names.push(obj.name); // adding the name to the names array
  }
}

console.log(names);

Answer №2

If you want to extract an array of names only, you can utilize the .map() and .concat() methods in JavaScript:

const info = [
  [{name:"Alex",age:"30"}],
  [{name:"Grace",age:"22"}], 
  [{name:"Leo",age:"54"}]
];

const names = [].concat(...info).map(({ name }) => name);

console.log(names);

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

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

Seeking ways to access a nested array object within an array object in React Native

Array [ Object { "resultlist": Array [ Object { "img": "https://www.act.com/image/cache/catalog/new%20thumbnails/Mifa%20A1BlacjkThumbnail-600x600.jpg", "name": "Mifa F1", "product_id": 87, "type": "product", ...

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

Receive the outcome once the form is submitted

Can someone provide quick assistance? I am looking to allow users to upload a CSV file for me to parse and analyze. Once the processing is done, I need to display the results back to the users. While uploading the file, I also need to ensure that the file ...

Add a new row to a table using auto increment feature in Javascript

I am having issues with inserting rows using a button in Javascript. When I click the button, rows are being inserted unexpectedly as shown in the images below. Additionally, I also need a delete row button to work in a similar manner. Thank you for any he ...

I want to import JSON information from a file to display on my website

I am trying to implement a JSON array on my webpage when a button or image is clicked. Here is the array I have: var products = [ { "productID":"1", "name":"Stark Navy", "url": "stark.jpg", "description": "Waterproof, double velcro straps", "price": " ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Angular is encountering a circular dependency while trying to access a property called 'lineno' that does not actually exist within the module exports

I am working on an Angular project and using the Vex template. My project utilizes Angular 9 and Node.js v15.2.0. Every time I run the project with the command ng serve -o, it displays a warning message. https://i.stack.imgur.com/8O9c1.png What could b ...

Encountered CS7036 Error after inserting the new code segment

What could be causing this error to occur? In my code, I have a class named Product with the following method: public void insertProduct(int cid, string name, string price, byte[] image, int quantity, string desc, int company, int compid) { DB db = ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Control the prompt with the Puppeteer typing function

Hello, I am currently attempting to log into a system that looks like the following: The input fields are labeled as username and password, with buttons labeled as login and cancel. I am trying to input data into these fields and click on the login ...

Alert users before visiting external websites

Is there a way to notify users about external pages without using popups like in the first example here: https://i.sstatic.net/5QJLu.png Instead of the unwanted code shown above, is there an alternative solution? Is there a different approach that can be ...

The method of inserting a JSON dates object to deactivate specific days

I am currently utilizing a date picker component that can be found at the following link: While attempting to use the disabledDays section below, I have encountered an issue where I am unable to apply all three options. The blockedDatesData option works o ...

Using Excel VBA to transfer a 2D array to a different worksheet

When working in VBA, I discovered a function that generates a 2D array called res. My goal is to transfer the array data to a different worksheet instead of the current one where the function is running. Even though this seems straightforward, my lack of e ...

Refreshing jQuery dataTable following AJAX completion

I encountered an issue when trying to reload my dataTable after performing a simple delete Ajax process. Initially, the dataTable is initialized and functions correctly as required upon page load. However, upon deleting a specific entry (row) using a butto ...

Upon employing the setTimeout method, the element with the id "sign-in-block" will have its display style set to "none" after a delay of 1000 milliseconds

I incorporated the setTimeout() function to make the HTML component appear for 1 second upon pageload. However, I would prefer this component not to load at all. Should I set the delay in the setTimeout() function to 0ms? Alternatively, is there another ...

What is the process for authenticating and sending a click conversion to Google Ads using a service account and the REST API with TypeScript?

I have attempted to authenticate using this documentation and to send conversions via REST API using this REST endpoint due to the absence of a Typescript/Javascript Client Library. However, I am encountering authentication issues. Once resolved, I aim to ...

Angular Search Panel

I'm having trouble with the Angular Search box not working when I try to run it locally on my computer. The same code works perfectly fine on platforms like codepen, plunker, and jsfiddle. Can someone help me figure out what's going wrong? .ex ...

Unable to display JSON data in table with AngularJS Rest Service

Here is the content of index.html: <!doctype html> <html> <head> <title>Batch Job Data</title> <link href="css/angular-bootstrap.css" rel="stylesheet"> <link href="css/styles.css" rel="stylesheet"> <meta ch ...

JS: Decreasing the counter while calling the hide() function

If I have a standard count <?php echo "Today (".mysql_num_rows($query)."); ?> It will display as Today (10) if there are 10 entries. Beneath this counter is a while() loop that displays all the rows in a <tr>. Within each <td> in the ...