utilizing array.map() to nest multiple layers of arrays

I am facing a challenge with a JavaScript array structure that contains three top-level objects. Each of these objects has an "teamLineup" array, which in turn holds two more objects named "team". These "team" objects have another array called "starters", where the player names are nested under the key "name". The structure of the top-level objects is as follows:

let game1 = {
  teamLineup: [{
    team: {
      actual: {
        starters: [{
          player: { name: 'Joe' },
          player: { name: 'Kim' }
        }]
      }
    }
  },{
    team: {
      actual: {
        starters: [{
          player: { name: 'John' },
          player: { name: 'Shauna' }
        }]
      }
    }
  }]
}

(game2....game3)

My objective is to simplify this original array into a single array containing only the player names presented as strings.

let games = [game1, game2, game3]

let allStartingPlayers = games.map(a => a.teamLineup.map( b => b.team.actual.starters.map(c => c.player.name)))

console.log(allStartingPlayers);

An example output could look like this:

[ [ [ 'Kim' ], [ 'Shauna' ] ],
  [ [ 'Nicole' ], [ 'Jennifer' ] ],
  [ [ 'Sandy' ], [ 'David' ] ] ]

This code currently encounters two issues. It only retrieves the second player's name from each "starters" array and generates three nested arrays instead of a flat structure.

Answer №1

Utilize 2 map functions, one for the main array and another for the starters array.

Afterwards, employ [].concat(...arr) to flatten the outcomes.

let game1 = { teamLineup: [{
    team: {
      actual: {
        starters: [
          {player: {name: 'Joe'}},
          {player: {name: 'Kim'}}
        ]
      }
    }
  },{
    team: {
      actual: {
        starters: [
          {player: {name: 'John'}},
          {player: {name: 'Shauna'}}
        ]
      }
    }
  }]
};

let game2 = { teamLineup: [{
    team: {
      actual: {
        starters: [
          {player: {name: 'Albert'}},
          {player: {name: 'Samantha'}}
        ]
      }
    }
  },{
    team: {
      actual: {
        starters: [
          {player: {name: 'Jina'}},
          {player: {name: 'Rob'}}
        ]
      }
    }
  }]
};

const games = [game1, game2];

const result = [].concat(...[].concat(...games.map(game => game.teamLineup.map(g => g.team.actual.starters.map(s => s.player.name)))));

console.log(result);

Answer №2

Your JSON structure needs some adjustments, especially with the starters array. Each player should be represented as a separate object.

To address the issue of multiple nested arrays, you can utilize forEach() method to loop through the objects and only extract the player names into the results array.

Check out the modified code snippet below:

let game1 = { teamLineup: [{
      team: {
        actual: {
          starters: [
            {player: {name: 'Joe'}},
            {player: {name: 'Kim'}}
          ]
        }
      }
    },{
      team: {
        actual: {
          starters: [
            {player: {name: 'John'}},
            {player: {name: 'Shauna'}}
          ]
        }
      }
    }]
  };

// Additional game objects

let games = [game1, game2, game3];

let allStartingPlayers = [];

games.forEach(a => a.teamLineup.forEach( b => b.team.actual.starters.forEach(c => allStartingPlayers.push(c.player.name))));

console.log(allStartingPlayers);

Answer №3

It seems like a curly bracket got lost along the way. In your example, you have written:

starters: [{
        player: {name: 'Joe'},
        player: {name: 'Kim'}
      }]

This actually means:

starters[{player:{name: 'Kim'}}]

To correct this, you may want to rewrite that part of the code as:

starters: [
       {player: {name: 'Joe'}},
       {player: {name: 'Kim'}}
        ]

In my opinion, you can then use a combination of reduce and map like so:

let allStartingPlayers = games.reduce((a,v) => a.concat(v.teamLineup.reduce( (a,b) =>a.concat(b.team.actual.starters.map(c => c.player.name)),[])),[]);

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

Having trouble displaying the collection data from firebase using React

I am having an issue retrieving a collection from firebase and then using a map function to loop through the documents and render some UI elements. The data is correctly logged in the console at line 20, however, the map function doesn't seem to be wo ...

What is the best way to bring Axios into the main.js file in a Vue project?

Recently, I encountered an issue with using axios in my Vue project. An error message stating that 'axios' is not defined popped up when I attempted to use axios.get() in my Home.vue file. I'm wondering if the problem lies within my configur ...

Combining for loops and async waterfall for optimal efficiency

Hey there, I'm just starting out with Nodejs and could really use some advice on writing more efficient code. Let me explain my issue. So, I have this function that is utilizing an async waterfall model. My goal is to call this function within a loop ...

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

JavaScript button is not functioning properly to increase or decrease the value in the input field

I'm facing an issue with the javascript increase/decrease buttons on my website. When I assign my JS variable as the class name of the input field, pressing the button results in all input fields being affected simultaneously: https://i.stack.imgur.c ...

I'm attempting to utilize AJAX to modify the sorting and ordering arguments in a WP_Query, yet I'm struggling to pinpoint the reason behind the failure of my code

After hours of non-stop work, about 6 solid hours with no breaks, I am baffled as to why this code isn't working. Let's take a look at the form in question: <div id="wp-ajax-filter-search" class="full"> <form ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Retrieving Content within <b></b> Tags from an RSS Feed XML (with Javascript/React)

After parsing an RSS Feed from Upwork, I have extracted job item data points such as title and link. However, a significant amount of the necessary information about each job (category, skills, etc) is buried within the "content" data item as one large blo ...

Show an SVG overlay when hovering over an image

Is there a way to create a hexagon shape around an image when it is hovered over using CSS only, even if the image itself has a circular border-radius of 50%? ...

The $scope variable does not sync with the express API

I have noticed that the static part of my app is loading fine. Recently, I integrated a service using Express as a simple API. However, when I attempt to set the #scope from my module's controller, it seems like it hasn't loaded at all. I am puzz ...

Tips for incorporating environment variables within a node configuration file

Assuming I have an environment variable $KEY Currently, I am executing KEY=$KEY babel-node build.js //using webpack to create a bundle of my code An issue arises in the JavaScript files bundled by webpack due to an import statement pointing to config.j ...

How can data be shared across different JavaScript functions?

I have two dropdown lists where I'm trying to pass the selected values for both to another function. I know that the way I am currently doing it is not correct, but I have been staring at this code for so long that I can't seem to find the probab ...

Encountering an error in resolving symbol values statically within the Angular module

Following a helpful guide, I have created the module below: @NgModule({ // ... }) export class MatchMediaModule { private static forRootHasAlreadyBeenCalled: boolean = false; // This method ensures that the providers of the feature module ar ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

connection and navigation hiccup

In my current project, I am utilizing Redux and React. Within App.js, I've implemented some Routes and also make use of the connect function from react-redux. In order to avoid any potential update blocking issues, I typically wrap my component in the ...

NodeJS produces identical outcomes for distinct requests

RESOLVED THANKS TO @Patrick Evans I am currently working on a personal web project and could use some assistance. In my website, users are prompted to upload a photo of their face. When the user clicks the "upload" button, the photo is sent with a request ...

The functionality of updating input values via jQuery AJAX in HTML response is currently not functioning as expected

Hello, I need some assistance. I'm encountering difficulty with jQuery in modifying HTML values that are dynamically inserted through an AJAX response. Here is the link to the JSFiddle. Below is the HTML on the page: <button id="test">test&l ...

The Angular scope remains stagnant even after applying changes

Having trouble updating a variable in the ng-repeat loop <div ng-controller="MapViewCtrl"> <a class="item item-avatar" ng-href="#/event/tabs/mapView" > <img src="img/location.jpg"/> <span cl ...

Exploring the Depackaging of ES6 Nested Objects

How can I implement ES6 with Destructuring to give users options? I'm having trouble dealing with nested objects and preventing the defaults from being overwritten by partial objects. Check out this simple example on MDN: function drawES6Chart({si ...