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

"Exploring the power of asynchronous programming with dynamic async await in

I am currently working on creating a versatile function that can dynamically call async functions. //passing the controller and functionName (string) function asyncAwaitCaller(controller, functionName) { let result = await controller[functionName]; } ...

Ways to examine attributes assigned in the controller.$onInit function in AngularJS

In a certain scenario, I am initializing some variables in the controller's $onInit method. How can I verify that these properties are being set correctly? Controller ctrl.$onInit = function () { ctrl.devices = _.cloneDeep(ctrl.formDevices); }; ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

Issues with CKEDITOR in Internet Explorer when multiple instances are used with different configuration files

My current challenge involves placing multiple CKEDITOR instances on a single page, each loading a different configuration file. While it functions correctly in Firefox (FF), Internet Explorer (IE) seems to apply the config file from the last instance on t ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

Update the formatting of the dates in the dateRangePicker

Utilizing a dateRangePicker, I am receiving dates in the format "mm-dd-yyyy". Below is my HTML code: <input type="text" name="TextDate" value="10/24/1984" /> Here is the script being used: <script> $(function() { $(&apos ...

Unexpected token "," in jQuery UI autocomplete error

Using the autocomplete feature works perfectly on my PC. However, I encounter an error when trying to test it on a mobile device. Do I need to utilize jQuery mobile in order for jQuery to function properly on mobile devices? Error message on line 3 of th ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

Accessing a file's source using the Box.net API and downloading the file contents

Recently, I've been busy working on a Web Application project (for fun) that focuses on editing files stored in the cloud. I'm utilizing the box.net API for this task, but I've come across a challenge - obtaining the source code of files. Un ...

Looking to personalize the MUI - datatable's toolbar and place the pagination at the top?

I successfully managed to hide the toolbar icon, but I am struggling with positioning pagination from bottom to top. Additionally, I am attempting to add two buttons (reset and apply) in the view-Column toolbar without any success in customizing the class. ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

What is the best way to locate the nearest marker using the Google Maps Direction Service?

Currently, I am engaged in the development of a Google Maps project where I am integrating markers retrieved from a database onto the map using the drawMarkers function. In addition to this, the Google Maps feature tracks your current location and refreshe ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

When new AJAX content is loaded, Isotope container fails to properly target the new objects and instead overlaps the existing ones

My webpage loads all content through an AJAX call. Initially, I tried placing my isotope initialization code inside a document ready function, but it didn't work as expected: $(function(){ container = $('#content'); contain ...