Finding the size of inner arrays through destructuring

I have a data array structured in the following pattern

data = [
          [0,
            [
             ['a', [{}, ..., {}]],
             ['b', [{}, ..., {}]] 
            ]
          ],
          [1,
            [
             ['a', [{}, ..., {}]],
             ['b', [{}, ..., {}]] 
            ]
          ],
          .
          .
          .
      ]

I am attempting to find the length of the innermost arrays of objects. My current approach is as follows:

foo = ([,[[,objects]]]) => console.log(objects.length);

data.foreach(foo);

Despite my expectation, instead of printing the length of each innermost array of objects, I am only getting multiple '1's printed to the console. It appears that objects is treated as an array with a single element rather than the entire array.

Is there a way to correct this issue while maintaining this specific pattern?

Additionally, is this method of accessing values known as destructuring in JavaScript?

Answer №1

Ah yes, here we have an illustration of destructuring assignment. Your code snippet demonstrates the concept effectively, though it appears to only output 2 results as it accesses only the first nested array within each array passed to the foo() function.

To log all the nested arrays of objects, a two-stage process is required. The initial stage involves isolating the inner arrays, followed by iterating over these inner arrays to obtain and display the lengths of the object arrays.

If we deconstruct the steps involved, it becomes easier to understand:

const foo = (array) => {
  console.log("array: ", array); // [0, [["a", [{}, {}, {}]], ["b", [{}, {}, {}]]]
  
  const [, inner] = array;
 
  console.log("inner: ", inner); // [["a", [{}, {}, {}]], ["b", [{}, {}, {}]]
  
  inner.forEach((arr) => {
    console.log("arr: ", arr); // ["a", [{}, {}, {}]]
    
    const [, object_arr] = arr;
    
    console.log("object_arr: ", object_arr); // [{}, {}, {}]
    console.log("object_arr.length: ", object_arr.length); // 3
  });
};

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

HighStocks should show categories instead of dates

The zoom function in HighCharts is what drew me to it initially. Everything was working perfectly until I encountered an issue that I can't seem to resolve. Here's my code snippet: http://jsfiddle.net/ma50685a/16/ $(function() { // Crea ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...

By employing the $watch method, the table disappears from the div element

I've integrated the isteven-multi-select directive for my multi-select dropdown functionality. By providing it with a list of thingsList, it generates a corresponding checkedList as I make selections. Initially, I used a button to confirm the selecti ...

Checkbox not working in Chrome [Version 101.0.4951.41 (Official Build) (64-bit)]

Update: It appears that the checkboxes in my project are not functioning correctly. Even when a standard checkbox was added to the HTML, it failed to respond to click events. I am currently developing a dat.gui menu for my THREE.JS project. You can find ...

Inside the Promise.then() function, iterate through the values using a for loop

I am curious about the behavior of promise.then() within a for loop in node.js. Consider the following code snippet: const arrayObject = [ { id: 1234, toto: 'abc' }, { id: 5678, toto: 'def' }, { id: 910, ...

Modifying a document by ID in Mongoose without altering a specific field

In my code, I have successfully established a new connection using Mongoose and implemented a schema. Retrieving attributes from the collection is also working as intended. However, when attempting to update my collection, I am encountering difficulties. T ...

Background Disappears Following Website Relocation

Recently, I created a PowerPoint presentation and then converted it to HTML using the conversion tool available at . The result on their website is exactly what I wanted, with a perfect layout. However, when I downloaded the zip file and uploaded the conte ...

Ways to handle a hidden element in Selenium Webdriver

Special features of this element:- <textarea id="txtSuffixTitle" class="form-control" tabindex="3" rows="2" placeholder="Suffix Title" name="txtSuffixTitle" maxlength="50" cols="20" style="display: none; visibility: hidden;">Suffix Title </text ...

Is there a way for me to access and retrieve the content of a tinymce textarea that has been modified

After clicking the 'Edit HTML Below then Click Display' button, my input texts work perfectly fine. However, I am facing issues with my tinymce textareas as they do not send the new value to the iframe when edited. How can I resolve this problem ...

AJAX cannot be used with the current session

I am facing an issue with a directory containing files that are used only as modal. These PHP files have the following format: "modal.filename.php". Here is an example: "modal.user.php": <?php session_start(); $_SESSION['test'] = 1; echo & ...

Three Divs stacked on top of each other, with varying heights based on

I am seeking a solution for creating a layout with three vertically stacked divs. The top div must have a fixed height of 60px. The middle div might contain content exceeding its height, therefore we've set it to overflow: auto. But regardless of th ...

Creating a Unique Navigation Bar Design in Bootstrap 4 with Custom Styling for Active

I have successfully added a navigation bar to my page, but I am currently facing issues with the active state. I want the navigation item to be underlined when it is active (when I am on that page) or when it is hovered over, and I also want brackets added ...

How come my Vue template files within other Vue files are not displaying properly?

I am currently working with three primary Vue files: index.vue.js: <template> <div class="tax-map-wrapper"> <h1>this is the page where the map renders</h1> <Map/> </div> </template> <script> ...

How to access an ejs variable within a Node.js environment using Javascript

As I experiment with my JavaScript code in an HTML file to interact with an ejs variable. Here is the Node.js code snippet: res.render('target.ejs', {data:user}); Everything works fine when I include this in my HTML file: <p> <h1> ...

Troubleshooting Vercel and Express DELETE request cross-origin resource sharing problem

Currently, I am in the process of developing an API using Vercel and ExpressJS. The GET and POST endpoints are functioning properly, however, I encountered an issue with the DELETE endpoint. When attempting to access the endpoint from my client-side JavaSc ...

What is the best way to create a line graph with D3.js in order to display data that is obtained from a server-side source?

I am trying to access data from a server side link, which is as follows: The data I want to retrieve is in JSON format and looks like this: {"Id":466,"Name":"korea", "Occurren ...

Analyzing an HTTP response containing a Content-Type header specifying image/jpeg

Currently, I am developing my first web application and the task at hand involves loading an image from a database and sending it to the client for display. On the server side, I have the following code: res.setHeader('Content-Type', pic.mimetyp ...

The functionality of removing a class on the body element is ineffective when using pagepiling.js

After creating a website using pagepiling.js, I implemented a script that adds the 'active' class to the section currently in view. My goal was to add a specific class to the body when my section1 is considered active. Here's the initial app ...

Adjust the z-index of the div to control the overflow scrollbar

I am facing an issue with a div that has a horizontal scrollbar and an image (or another div) positioned over the entire page using absolute positioning. The problem is I wish to scroll the div that is beside the image. For anchor links (a), I have set the ...

Exploring the capabilities of jest-next-dynamic through dynamic imports in Jest testing

Currently, I am in the process of testing dynamic imports in Next.js version 10.2.3. To achieve this, I decided to utilize the jest-next-dynamic library to prevent any potential errors from occurring. However, during my testing, I encountered a TypeError ...