Is there a way to isolate nested forEach loops from each other?

Lately, I've been working hard to streamline my code and eliminate nested for-loops / forEach methods in order to optimize the process. However, I've hit a roadblock with a specific task. I have an array of objects that includes another array of objects within it. I know how to extract attributes from the inner array using separate functions, but my challenge is extracting attributes from both arrays without resorting to nested loops.

Below is an example of the data structure:

let data = [{Id: '1234', Server: 'prime', Status: 'open', Connections: [{Type: 'xxr', ConID: '1222'}]},
 {Id: '1214', Server: 'prime', Status: 'open', Connections: [{Type: 'xxh', ConID: '1111'}, {Type: 'xxh', ConID: '1112'}]},
 {Id: '1233', Server: 'tif', Status: 'closed', Connections: [{Type: 'xml', ConID: '1212'}, {Type: 'xxr', ConID: '1233'}, {Type: 'xxh', ConID: '1111'}]}]

The current method involves pushing the necessary data to a new array:

let newArray = [];

  data.forEach(server => { 
            let temp = server.Connections;
            temp.forEach(obj => {

                let newObj = {
                    ServerID: server.ID,
                    Server: server.Server,
                    Status: server.Status,
                    ConnectionID: obj.ConID
                }
                newArray.push(newObj);
            })
        })

I am looking for a way to potentially use map instead of forEach to populate newArray, while still accessing attributes from both arrays simultaneously. Any suggestions or solutions would be greatly appreciated!

Answer ā„–1

Utilize the flatMap function within Arrays.

let freshArray = data.flatMap(server => server.Connections.map(conn => ({
    ServerID: server.Id,
    Server: server.Server,
    Status: server.Status,
    ConnectionID: conn.ConID
})));

Answer ā„–2

One way to handle nested loops is by utilizing the .map() function. This involves nesting multiple .map() operations and then using .flat() on the resulting array of arrays.

let updatedArray = data.map(server => {
    return server.Connections.map(obj => {
        return {
            ServerID: server.ID,
            Server: server.Server,
            Status: server.Status,
            ConnectionID: obj.ConID
        }
    });
}).flat();

Alternatively, you can use .flatMap() for the top level .map() operation to combine both mapping and flattening actions. In some cases, .flatMap() may offer slightly better efficiency.

let updatedArray = data.flatMap(server => {
    return server.Connections.map(obj => {
        return {
            ServerID: server.ID,
            Server: server.Server,
            Status: server.Status,
            ConnectionID: obj.ConID
        }
    });
});

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

Angular 2: Dynamically positioning content within a div overlay

I have made some customizations to a PrimeNg TabView and placed it inside a custom component to achieve the following: https://i.sstatic.net/mjWED.gif As you can see in the image, the tabview content is set to overflow-x: hidden to enhance the appearance ...

Ways to Resolve the Error "Uncaught TypeError: Cannot Assign Value to Undefined Property '0'"

After experimenting with the code below, I discovered that when arrays (bill, tipValue, totalAmmount) are declared within the object method, I encounter a "cannot set property '0' undefined" error. However, if the same arrays are declared outside ...

Is it possible to utilize BootstrapVue alongside Vue.Draggable for dragging and dropping items between a list and a b-table?

Would it be feasible to integrate Vue.Draggable with the Table component from BootstrapVue? Additionally, can items be dragged from a list and dropped into a column within a B-table, resulting in a new field named after the dropped item? Thank you for yo ...

Top strategy for managing numerous click occurrences

When a link is clicked in my application, I want to trigger a specific action. For instance, I am currently working on a manual that contains numerous internal links. At the moment, I am handling them individually like this: function waitForClick() { ...

Modifying `msg.sender` in Solidity and Ether.js

I have a Smart Contract written in Solidity. Within this contract, there is a function called makeMarketItem. function makeMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { IERC721(nftContract). ...

When sending a POST request, the req.body.someElement parameter is not defined

Encountering an issue with a post request, as req.body is returning undefined values. Despite researching on Google and Stack Overflow, the provided solutions have not resolved the problem. Although logging the name shows a value, trying to access req.body ...

Combining arrays with varying lengths using PHP

If you have two arrays set up in the following way: $arr1 = array( array('position' => 1), array('position' => 2), array('position' => 3), array('position' => 4), array('position' => 5), arr ...

What is the procedure for generating a mouse event for clicking a tab in Selenium WebDriver?

As I work with Selenium WebDriver and Java, there is a tab named PR Per Product. Under the PR Reports tab, there are multiple tabs. In the PR tab, I used: WebElement menuHoverLink = driver.findElement(By.id("ext-pr")); actions.moveToElement(menuHoverLink) ...

gulp-watch does not monitor files that are newly created or deleted

Currently working on a task: gulp.task('assetsInject', function () { gulp.src(paths.index) .pipe(plugins.inject( gulp.src(paths.scripts, {read: false}), { addRootSlash: false } ...

Ignoring templateUrl in AngularJS and Karma-Jasmine to prevent the occurrence of "Unexpected request: GET .../.html" error

Currently, I am developing an AngularJS application using ES6 in order to minimize the amount of work needed for transitioning to AngularJS 2.0. However, I have encountered some complexity when it comes to performing unit tests. My main focus now is to t ...

What is the best way to download a modified canvas with filters using the solutions from stackoverflow?

There have been numerous inquiries regarding how to apply CSS filters to an image, with some solutions that don't utilize CSS filters but still achieve the desired outcome. However, for someone new to JavaScript like myself, these answers can be confu ...

If the JSON file exists, load it and add new data without recreating the file or overwriting existing data

Currently, I am in the process of developing a function called createOrLoadJSON(). This function is responsible for checking whether an existing JSON file exists within the application. If the file does not exist, it should create a new file named "userDat ...

Switching between all tabs simultaneously in an MDX page (React + Gatsby + MDX) using @reach/tabs

Creating a Tab component for a Gatsby site has proved to be a bit tricky. Imagine having a page with multiple tabs all labeled the same: Heading 1 First tab block Tab 1 | Tab 2 Content Tab 1 Second tab block Tab 1 | Tab 2 Content Tab 1 for the second bl ...

What are the disadvantages associated with the different methods of submitting data?

My goal is to create an Online testing platform. I have come across two different approaches to verify user-selected answers. Approach 1 <div class="qContainer" index="0"> Who holds the record for scoring 100 centuries in International cricke ...

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

Creating an Azure function that utilizes an HTTP trigger to handle and process HTTP POST requests containing multipart/form-data

I am currently utilizing Azure function apps with C# (or NodeJS). How can I create an http post request to accomplish the following task? The Http trigger function app needs to send an HTTP request to a different server to retrieve some data. Parse the in ...

Having an issue with ng-model not functioning correctly in md-menu with AngularJS material

I'm currently using md-menu from Angular Material and I have integrated a search box with ng-model in the list. However, I am facing an issue where I cannot access ng-model because 'md-menu-content' is out of scope. Here is my code: <div ...

What is the process for changing a jQuery countdown function to a count-up function?

I'm currently developing a portal that utilizes a jquery plugin known as countdown from the link https://github.com/hilios/jQuery.countdown Here is the code snippet: $(document).ready(function(){ $("#countdown").countdown("2022/06/25 ...

Should you include the dollar sign in a Vue HTML variable or not?

Iā€™m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Generate a new passport session for a user who is currently logged in

I am currently utilizing passport js for handling the login registration process. After a new user logs in, a custom cookie is generated on the browser containing a unique key from the database. Here's how the program operates: When a new user logs ...