Transform a collection of objects into an array

In my data array, I have various groups and types:

const data = [
  {
    groupName: 'groupName1',
    types: [
      {
        name: 'name1',
        displayName: 'displayName1'
      },
      {
        name: 'name2',
        displayName: 'displayName2'
      },
    ]
  },
  {
    groupName: 'groupName2',
    types: [
      {
        name: 'name3',
        displayName: 'displayName3'
      },
      {
        name: 'name4',
        displayName: 'displayName4'
      },
    ]
  },
]

My goal is to modify this data array by adding a groupName field to each object. The desired output should be an array with objects as shown below:

const resultData = [
  {
    groupName: 'groupName1',
    name: 'name1',
    displayName: 'displayName1'
  },
  {
    groupName: 'groupName1',
    name: 'name2',
    displayName: 'displayName2'
  },
  {
    groupName: 'groupName2',
    name: 'name3',
    displayName: 'displayName3'
  },
  {
    groupName: 'groupName2',
    name: 'name4',
    displayName: 'displayName4'
  },
]

I attempted to achieve this using the map array method

const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]

const resultData = data.map((item) => {
  item.types.map((item1) => {
    return {
      ...item1,
      groupName: item.groupName
    }
  })

  return item
})

console.log(resultData)

However, this approach did not provide the desired array. Can you suggest an alternative method to transform this array to have the correct structure? Thank you in advance!

Answer №1

Optimize the code by replacing the outer Array.map() call with Array.flatMap() to simplify the array structure. Make sure to return the modified data from the internal map call instead of the original item.

const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]

const resultData = data.flatMap(({ types, groupName }) => 
  types.map(item => ({
    ...item,
    groupName
  }))
)

console.log(resultData)

Answer №2

To solve this problem, my go-to method would be utilizing the reduce function.

data.reduce((accumulator, {types, groupName}) => accumulator.concat(types.map(item => ({...item, groupName}))), []);

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

This function appears to have an excessive number of statements, totaling 41 in total

Currently, I am using this controller: .controller('ctrl', function($scope, $rootScope, $timeout, $alert, $location, $tooltip, $popover, BetSlipFactory, AccordionsFactory, AuthFac ...

What is the best way to fetch a partial JSON response object from an API using JavaScript?

Currently, I am utilizing the One Bus Away API, returning a response object in this format: { "code": 200, "currentTime": 1504150060044, "data": { "entry": { "arrivalsAndDepartures": [ {AnD_item1 ...

Clicking on a flex card will trigger the opening of a new page where the parsed data will be displayed in a stylish manner using JavaScript

Currently, I am attempting to showcase the data retrieved from the following URL: . My objective is to format the parsed data with a specific style. However, I have encountered difficulties accomplishing this using `window.open()`. Any assistance in resolv ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...

Exploring the wonders of looping through arrays with JavaScript and jQuery

I am having trouble getting this function to work properly. My goal is to replace certain characters when a key is pressed. The code works fine using the variable `replace_list` instead of `replace_list["russian"]`, but I actually need different "replace ...

Are there alternative approaches to launching processes aside from the functions found in child_process?

Having trouble with NodeJS child_process in my specific use case. Are there other methods available to start processes from a node.js application? So far, Google has only been pointing me towards child_process for all of my inquiries. Edit I am looking to ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. https://i.sstatic.net/W7Fzi.png Issues with animation arise when you click the "Start" button again. The animation resets and begins ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

React hooks eliminating unnecessary rendering

Having recently delved into React and hooks, I'm facing an issue with refreshing the list of files in my app after clicking on the convert button. The correct file only shows up if I manually refresh the page. The React part of the code involves uplo ...

What is the best way to apply dynamic wrapping of a substring with a component in Vue.js?

My Objective My goal is to take a user input string and render it with specific substrings wrapped in a component. Specifically, I am looking to identify dates within the string using a regex pattern and then wrap these dates in a Vuetify chip. Progress ...

The error message "gaq is not defined in opencart 2.0" indicates

While attempting to monitor transactions in OpenCart, I encountered the following error message: Uncaught ReferenceError: _gaq is not defined(anonymous function) This is the method I am using for tracking in my catalog/view/theme/default/template/commo ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

Why does the Element.style.left property keep rejecting my input value?

I have encountered a problem with the positioning of elements, specifically with the 'left' property. I've designed a rectangular block using CSS and rotated it by 0.17 radians in JavaScript. Now, my aim is to make the block move diagonally ...

Is it possible to organize multiple tables within a single JSON structure without relying on JArray?

I am currently developing a program similar to IMDB, where I am showcasing individuals with a filmography, discography, and more. After setting up my view in MVVM, I am now working on serializing my JSON data to align with it. At the moment, I am consolida ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

Glitched Water Reflection in THREE.js

Creating a water scene using JavaScript. I followed the official examples to set up the scene, but the reflection seems off after loading an external GLTF model. Initially everything looks fine, but once I start moving the camera, things go awry. I suspe ...

Quasar unable to detect vuex store

I am currently working with the Quasar framework and I am trying to add a store module. Despite running the quasar new store <name> command, I keep receiving the message "No vuex store detected" in the browser console. Any idea where the issue migh ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...