How to loop through nested objects in JavaScript without using jQuery

Currently attempting to loop through a nested object.


array=[
  {
    id: 2,
    items: [
      {
        id: 12
      },
      {
        id: 13
      },
      {
        id: 14
      }
    ]
  },
  {
    id: 3,
    items: [
      {
        id: 15
      },
      {
        id: 16
      },
      {
        id: 17
      },
      {
        id: 18
      },
      {
        id: 19
      }
    ]
  },
  {
    id: 4,
    items: [
      {
        id: 20
      },
      {
        id: 21
      }
    ]
  },
  {
    id: 5,
    items: [
      {
        id: 22
      }
    ]
  }
];

The goal is to consolidate all IDs into one array, following the initial data structure. Here's an example of the desired output:


arrayOfId = [2, 12, 13, 14, 3, 15, 16, 17, 18, 19, 4, 20, 21, 5, 22];

I have attempted some solutions with jQuery examples, but my project utilizes Angular. Seeking guidance on achieving this with vanilla JS or Angular specifics.

Appreciate any assistance!

Answer №1

It's really quite straightforward.

  1. Calculate the length of the array.
  2. Iterate through the array and create a new array (ids) with the current id value.
  3. Determine the length of the nested array.
  4. Loop through the nested array and add the nested ids to the main array.

var l=array.length,i=0,ids=[];
for(;i<l;i++){
 ids.push(array[i].id);
 var nested=array[i].items,nl=nested.length,j=0;
 for(;j<nl;ids.push(nested[j++].id));
};

console.log(ids);
alert(ids);

//ids=[2,12,13,14,3,15,16,17,18,19,4,20,21,5,22];

This example demonstrates different ways to implement the for loop. By caching variables like the array length and the nested arrays, the performance is enhanced. It should be noted that for simple operations such as looping through multidimensional arrays/objects, using native javascript functions like forEach, map, or filter is not recommended due to significant performance drawbacks compared to traditional while & for loops (1). They are approximately 3-4 times slower. However, if the multidimensional array is small and users have modern browsers, the map solution can offer a more concise alternative (2).

DEMO

http://jsfiddle.net/axaog3n2/1/

1 https://jsperf.com/for-vs-foreach/2

2 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

If you have any inquiries, feel free to ask.

Answer №2

An effective technique is to incorporate a for loop within another for loop.

for (var k = 0; k < array.length; k++) {
  arrayOfId.push(array[k].id);
  for (var m = 0; m < array[k].length; m++) {
    arrayOfId.push(array[k][m]);
  }
}

Answer №3

Implement Array.map

//Using Array.map to create a 2D array of ids [[2,3],[2,3]]
var ids = array.map(function(item) {
    return item.items.map(function(obj) {
        return obj.id
    })
});

//Flattening and merging the array
var idList = [];
idList = idList.concat.apply(idList , ids);

//Final output:
//[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]

See it in action: http://jsfiddle.net/2kmozrr7/

Answer №4

Here is a basic for loop example:

var arrayIds = [];
for (var index = 0; index < myArray.length; index++) {
    arrayIds.push(myArray[index].id);
    if (myArray[index]['items'] != undefined && myArray[index].items.length > 0) {
        for(var innerIndex = 0; innerIndex < myArray[index].items.length; innerIndex++) {
            arrayIds.push(myArray[index].items[innerIndex].id);
        }
    }

}

Answer №5

var identifiers = [];
for (var i = 0; i < array.length; i++) {
    identifiers.push(array[i].id);
    if (array[i].items) {
        var itemsArray = array[i].items;
        for (var j = 0; j < itemsArray.length; j++) {
            if (itemsArray[j].id) {
                identifiers.push(itemsArray[j].id);
            }
        }
    }
}

If you need to go deeper than this level of nesting, it's advisable to utilize a recursive function.

var output = [];
function process(arr, output) {
    for (var i = 0; i < arr.length; i++) {
        output.push(output[i].id);
        if (output[i].items) {
            process(output[i].items, output);
        }
    }
}
process(thatObject, output);

Answer №6

// an array is created to store the result
var newArray = [];
// looping through the source array
array.forEach(function (outerArray) {
    // fetching the id property and adding it to the new array
    newArray.push(outerArray.id);
    // iterating through the items in the outer array
    outerArray.items.forEach(function (innerArray) {
        // grabbing the id property of the inner array object and pushing it to the new array
        newArray.push(innerArray.id);
    });
});

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

How to retrieve nested menu items within the scope by utilizing JSON and AngularJS

I have recently started working with angular and am facing difficulty in accessing the submenu items within my angular application. While I can successfully access the top level menu items, I am struggling to retrieve the second level items. Here is a sni ...

Retrieve keys by reading JSON data stored as a string

Is it possible to read JSON from a string and iterate through it without knowing the key it stores? Typically, JSON is in key value pair format, right? I am aware that I can use: dynamic dynamicJson = JsonConvert.DeserializeObject(json); However, I do n ...

AngularJS - ensuring that updates in child contexts are reflected in the parent context

I am currently working on an AngularJS application that includes a shell page. The shell page has a dropdown menu that lists various locations. Within one of the internal pages, there is a feature that allows users to add new locations. Once a new location ...

When using body-parser, req.body may sometimes unexpectedly return undefined

My current project involves creating an API that handles POST requests for user creation. Unfortunately, I'm encountering undefined errors for all the req.body calls. Here's a simplified overview of how my application is structured: User control ...

The compass is currently not displaying the magnetometer values

Hello! I am currently working on a code that displays the values of the magnetometer's (x, y, z) components. Unfortunately, the issue I am facing is that the code keeps returning a "null" value continuously. You can find the link to my expo snack here ...

Set a variable in MongoDB to retrieve the results of the find() method and convert them

Struggling to make this code function properly var data = db.collection('mycollection', function(er, collection) { return collection.find().toArray(); }); The variable data is not returning an array as expected. Uncle ...

Choosing several options from a list with React Native

I have a list created using the data.map() method, but I am encountering an issue where it only allows selection of one item at a time. I actually want to be able to select multiple items from the list. Even though I had designed the list to allow selectin ...

Creating a mask for both integer and decimal values in jQuery

I have created a validation mask in my code to verify user input when onBlur unitprmask:/^\d+,\d{1,1}$/, However, the current mask only allows for decimal numbers, requiring at least one decimal place. I want users to be able to enter whole in ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Adjust the styling of the anchor tag within the selected div by utilizing jQuery

I am struggling with changing the color of a specific anchor tag when clicked inside a div with class .product_wishlist. Currently, all anchor tags within .pw div are changing colors. Is there a way to apply selected css only to the clicked element? Any he ...

Uploading a JSON file to myjson.com using a jQuery PUT request in Node.js

As a novice in javascript, I have successfully retrieved a JSON object from on my HTML page using AJAX with the following code: $.getJSON("https://api.myjson.com/bins/bjm28", function (data) { $.each(data, function (index, value) { console.log ...

Having trouble getting the dashed line material in three.js to work on LineSegments

I'm having trouble in Three.js attempting to create a cube with dashed line edges, but the lines are still appearing solid. Below is my code snippet: var mat_line = new THREE.LineDashedMaterial( { color: "black", dashSize: 1, gapSize: 1 } ); ...

What is the method for retrieving the value assigned to body.data[0].images.fixed_height.url?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script type="text/javascript"> var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=ryan+gosling&api_key=dc6zaTOxFJmzC&limit=5"); ...

Implementing JSON and JQuery to dynamically update ActionLinks in an MVC table

Here's the HTML code I'm using to display image actions inside a table element: <%= Html.ActionLink("[EditImg]", "Edit", new { id = item.GrossBaseReconId }, new { id = "BaseReconEdit", rowsid = item.GrossBaseReconId }).Replace("[EditImg]", "& ...

Navigating the perplexing world of Jquery, ajax, and the enigma of the amp

After reading up on best practices, I've learned the importance of encoding any URL passed to another source. This article explains it further: I recently wanted to share the current track time of a song I was listening to. With the help of the youru ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Exploring the impact of naming variables in JavaScript versus not naming them

"use script"; var user = { name: "John Doe", career: "Civil Engineer", socialMedia: { fb: "www.facebook.com/johndoe", twitter: "www.twitter.com/johndoe" }, about: function() { console.log("My name is " + this.na ...

Testing a Vue component that includes a Vuetify data table with customized slots

I have been struggling to write a Jest test for a simple component that includes a nested v-data-table component. While the page renders correctly in the browser, my test keeps failing. The problem seems to lie with the template I am using for the slot - ...

Tips for managing variations in the naming conventions of JSON fields in request bodies when transferring data from JavaScript to Python using Django REST framework (DRF)

As I work on creating Rest APIs in Python DRF and consuming them in angularJS, I am encountering a challenge related to the naming conventions of variables in JavaScript and Python. JavaScript typically uses camel case for variable names, while Python fol ...