"Utilize JavaScript to assign array values to the main object for efficient data

I am looking to parse a modified JSON file to create separate objects for each team and player. I want each object to have a key for the team name and the player name.

Using JavaScript, how can I achieve the following structure:

[
{ name: 'Dallas Stars', playerName: 'Alexander Radulov'},
{ name: 'Dallas Stars', playerName: 'Ben Bishop'},
{ name: 'Dallas Stars', playerName: 'Jamie Benn'}
...
{ name: 'Columbus Blue Jackets', playerName: 'Pierre-Luc Dubois'}
]

Given this JSON data:

[ { name: 'Dallas Stars',
        roster:
         [ 'Alexander Radulov',
           'Ben Bishop',
           'Jamie Benn',
           'Tyler Pitlick',
           'Miro Heiskanen' ] },
      { name: 'Los Angeles Kings',
        roster:
         [ 'Jonathan Quick',
           'Jonny Brodzinski',
           'Oscar Fantenberg' ] },
      { name: 'San Jose Sharks',
        roster:
         [ 'Joe Thornton',
           'Brent Burns',
           'Joe Pavelski',
           'Antti Suomela' ] },
      { name: 'Columbus Blue Jackets',
        roster:
         [ 'Sonny Milano',
           'Brandon Dubinsky',
           'Nick Foligno',
           'Pierre-Luc Dubois' ] } ]

I am attempting to link each team name to individual players. I have explored different lodash functions but have not yet found the solution.

Is it possible to utilize a flat map and duplicate the team name for each player?

Answer №1

To effectively process the data, you should iterate through the main array elements and then within each of those, loop through the `roster` as well. Using the `reduce` method is commonly the best approach for transforming an array into another array in a non-one-to-one manner:

const teams=[{name:'Dallas Stars',roster:['Alexander Radulov','Ben Bishop','Jamie Benn','Tyler Pitlick','Miro Heiskanen']},{name:'Los Angeles Kings',roster:['Jonathan Quick','Jonny Brodzinski','Oscar Fantenberg']},{name:'San Jose Sharks',roster:['Joe Thornton','Brent Burns','Joe Pavelski','Antti Suomela']},{name:'Columbus Blue Jackets',roster:['Sonny Milano','Brandon Dubinsky','Nick Foligno','Pierre-Luc Dubois']}];

const players = teams.reduce((acc, { name, roster }) => {
  roster.forEach((playerName) => {
    acc.push({ name, playerName });
  });
  return acc;
}, []);
console.log(players);

Answer №2

Utilizing the map and flat functions is another option.

Start by mapping over the original array, then for each item being "mapped," further map over its roster to construct the desired object. Finally, as the resulting array will be 2-dimensional, flatten it:

var data = [{ name: 'Dallas Stars', roster: ['Alexander Radulov', 'Ben Bishop', 'Jamie Benn', 'Tyler Pitlick', 'Miro Heiskanen' ] }, { name: 'Los Angeles Kings', roster: ['Jonathan Quick', 'Jonny Brodzinski', 'Oscar Fantenberg' ] }, { name: 'San Jose Sharks', roster: ['Joe Thornton', 'Brent Burns', 'Joe Pavelski', 'Antti Suomela' ] }, { name: 'Columbus Blue Jackets', roster: ['Sonny Milano', 'Brandon Dubinsky', 'Nick Foligno', 'Pierre-Luc Dubois' ] } ];

var res = data
  .map(({name, roster}) =>
    roster.map(playerName => ({name, playerName})))
  .flat();

console.log(res);

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 with submitting the AJAX form when trying to rate something

Need help with the review rating code. The form submission does not save data to the database. Any assistance is appreciated. <form id="commentform" method="POST" action="#" class="form form-inline form-contact"> <p class="push-down-20"> ...

Plotting a course on Google Maps using various sets of latitude and longitude coordinates retrieved from a database

I've successfully created PHP and JavaScript code that retrieves longitude and latitude information from a database and places markers on a Google map based on these values. Now, I want to connect these markers and plot a route on the map. How can I ...

Position SVG's in relation to one another

I have two SVG's and I'm looking to position the second SVG in the top right corner of the first SVG. In this example, I want to place the exclamation SVG in the TOP RIGHT corner of the first SVG. Can someone provide guidance on what changes I n ...

What could be causing my Google Chrome extension to only allow me to open 25 tabs instead of more?

Having a frustrating issue with my code that is causing problems when used as a Chrome Extension. Despite checking and confirming that the code should work correctly, it seems to stop opening pages after tab 25. I have verified that the code attempts to o ...

Even though I have successfully stored a key value pair in LocalStorage using JSON stringify and setItem, the data does not persist after the page is refreshed

I recently developed a Todo application that runs smoothly, except for one crucial issue - the localStorage data does not persist after refreshing the page. Initially, the localStorage operations functioned properly when there were fewer event handlers in ...

Passing hooks down in React leads to input losing focus due to rerendering

I have a parent component where I initialize some state, and then pass it down to the child components for updating. Unfortunately, when the update occurs, the component tree is re-rendered causing my inputs to lose focus. Even adding a `key` did not resol ...

How to programmatically clear an input field in Angular using Bootstrap's typeahead feature

My current setup involves utilizing a form to populate a list displayed alongside the form. The markup looks like: <form name="stateForm"> <input type="text" ng-model="model.name" typeahead="state for state in states | filter:$viewValue"> ...

Error: Unable to access the 'comments' property of a null value

Encountering an issue when trying to add comments to a post, resulting in the error message: TypeError: Cannot read property 'comments' of null Post routes: router.post("/", async (req, res) => { console.log(req.params); Post.findById(r ...

Replace a string in an array using JavaScript

I may be overlooking something very obvious, but here is my dilemma. I am trying to convert [ 'hr' ] into [ '* * *' ]. This is what I tried: var hr = jsonml[i] console.log(hr) // outputs: [ 'hr' ] hr.replace(/hr/g, '* * ...

What is the best way to keep a checkbox unchecked after clicking cancel?

I'm working on a bootbox script that triggers a customized alert. I need the checkbox that triggers the alert to be unchecked when the user clicks cancel. Here is the checkbox when it's checked <div class="checkbox"> <label> ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

Testing a directive that has templates all contained within a single file with script tags

I'm struggling to include my directive's templates in my Karma unit tests. The templates are all in one file within different script tags. The error message I encounter is: PhantomJS 1.9 (Linux) ERROR SyntaxError: Parse error at /var/www/html ...

Can a web application determine if Microsoft Excel has been installed?

Currently, I am developing a web application using ASP.NET that includes certain functionalities which rely on Microsoft Excel being installed on the user's device. In case Excel is not available, I would prefer to deactivate these features. I am foc ...

The Sluggishness of MongoDB Aggregation in Determining Distinct IDs within Retrieved Documents

Not only does my Mongo view return a filtered set of documents to the end user, but it also runs a couple of functions to calculate running totals. Strangely though, while my find() operation is blazingly fast (225ms), this additional aggregation process t ...

When transferring files using formData via axios, the server is unable to interpret the data

`` In my quest to figure out how to send a file from a client using an input type=file to an API, I came across the suggestion to use formData. Following some examples I found, I implemented this approach, but upon checking the data on the server side, it ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

What is the Python technique for arranging row values in an Excel file using a dictionary?

Suppose an Excel file contains 2 rows: 0.296178 0.434362 0.033033 0.758968 0.559323 0.455792 0.780323 0.770423 Is there a way to arrange the values in each row from highest to lowest using a dictionary? For instance, for row 1, the dict ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

Is it possible to use an Ajax callback function to add a select dropdown HTML to a table

I am currently in the process of using jQuery to append some HTML with the code provided below. My main objective is to select an option based on AJAX response data and create a select dropdown menu. However, the variable scope of sOut doesn't seem to ...