Is there a way to transform individual data into a collective group dataset?

Here is the input data provided:


data = [
    { name: "John Cena", groupName: "WWE" },
    { name: "Nandini", groupName: null },
    { name: "Rock", groupName: "WWE" },
    { name: "Vinay", groupName: null },
    { name: "Rey Mesterio", groupName: "WWE" },
    { name: "Gokul", groupName: "FSD" },
    { name: "Rohitha", groupName: "FSD" }
];

The desired output format should be as follows:


requiredFormat = [
    { name: "FSD", value: ["Gokul", "Rohitha"] },
    { name: "WWE", value: ["John Cena", "Rock", "Rey Mesterio"] },
    { name: null, value: ["Nandini", "Vinay"] }
];

Answer №1

To achieve this, utilize the reduce function while also verifying if a certain array value is already present. If it is, then add to it; if not, create a new one.

const info = [
  { title: "John Cena", category: "WWE" },
  { title: "Nandini", category: null },
  { title: "Rock", category: "WWE" },
  { title: "Vinay", category: null },
  { title: "Rey Mesterio", category: "WWE" },
  { title: "Gokul", category: "FSD" },
  { title: "Rohitha", category: "FSD" }
];

const desiredStructure = info.reduce((accumulator, element) => {
  const located = accumulator.find(({ title }) => title === element.category);
  if (located) located.value.push(element.title);
  else accumulator.push({ title: element.category, value: [element.title] })
  return accumulator;
}, []);

console.log(desiredStructure);

Answer №2

Utilize Array.reduce to address the issue at hand

const information = [
    { username: "John Cena", team: "WWE" },
    { username: "Nandini", team: null },
    { username: "Rock", team: "WWE" },
    { username: "Vinay", team: null },
    { username: "Rey Mesterio", team: "WWE" },
    { username: "Gokul", team: "FSD" },
    { username: "Rohitha", team: "FSD" }
  ];

const modifiedData = data.reduce((accumulator, element, index) => {
    const team = accumulator.find(group => group.username === element.team);
    if (!team) {
        accumulator.push({username: element.team, value: [element.username]})
    } else {
        team.value.push(element.username);
    }
    return accumulator;
}, []);

console.log(modifiedData);

Answer №3

To simplify the process, you can use the reduce method in combination with Object.values().

var data = [ { name: "John Cena", groupName: "WWE" }, { name: "Nandini", groupName: null }, { name: "Rock", groupName: "WWE" }, { name: "Vinay", groupName: null }, { name: "Rey Mesterio", groupName: "WWE" }, { name: "Gokul", groupName: "FSD" }, { name: "Rohitha", groupName: "FSD" } ];

var result = Object.values(data.reduce((acc, {name, groupName})=>{
    acc[groupName] =acc[groupName] || {name:groupName, value:[]};
    acc[groupName].value.push(name);
    return acc;
},{}));

console.log(result);

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

Creating MySQL query results in Node.js manufacturing process

I am looking to format the MySQL result in Node.js in a specific way. The desired result format should look like this: [ { "m_idx" :1 , "contents" : { "m_name" : "a", ...

What is the process for browserifying the net.Socket module in Node.js?

I'm exploring ways to connect and query my MS SQL database from JavaScript in a web browser (specifically Chrome, not IE as I don't want to use ActiveX controls). I came across this Node library called Tedious and Browserify to help with this tas ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

What is the best way to cancel a setTimeout in a different function within a React JS application?

I'm currently working with the following code snippet: redTimeout = () => { setTimeout(() => { this.props.redBoxScore(); this.setState({ overlayContainer: 'none' }); }, 5000); } In addition, I h ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...

Issue with Vuex not functioning properly in Nuxt.js

I'm facing an issue with setting the state in Vuex on my Nuxt.js App. It seems to not be working correctly. So, here is how I am trying to set the state using the fetch method: fetch({app, store, route}) { app.$axios.$get(`apps/${route.params ...

When trying to save a child entity, TypeORM's lazy loading feature fails to update

I've been troubleshooting an issue and trying various methods to resolve it, but I haven't had any success. Hopefully, someone here can assist me. Essentially, I have a one-to-one relationship that needs to be lazy-loaded. The relationship tree ...

Using JSP to send variables from an external Javascript file

After creating a timer function, I am looking to display the results on a different page. The setup involves a JSP file calling functions from a separate JS file in order to output the information to another screen: Instructions in the JSP file: <butt ...

Using jQuery to add the name of a file to FormData and fetching it in a PHP script

I've been working on a JS code snippet dedicated to uploading images based on their file paths: var data = new FormData(); data.append('fileName', fileName); data.append('file', file); $.ajax({ url : dbPath + "upload-file.php" ...

Creating a Wordpress Metabox that utilizes radio inputs generated with Javascript instead of the traditional checked() function in Javascript as an alternative

Despite my efforts to find a solution on various forums, I am still stuck with this issue without making any progress. The code snippet below contains two Radio inputs. These inputs are generated on the post edit page of Wordpress CMS and their values com ...

Python: How can I optimize the process of generating a list of lists where each element is unique based on another embedded list?

My REST API receives arbitrary data that I need to sort and convert into a list of lists, for example: attributes = [ ['apple', 'banana', 'orange'], ['25'], ['red', 'yellow'] ] I am looking to cr ...

Encountering the issue of "Cannot read properties of undefined" while attempting to pass data to a prop

Currently, I am developing a Vue application that heavily relies on charts. The issue lies in the fact that I am fetching data from the database individually for each chart component, resulting in multiple calls and a slower page load time. I am looking to ...

Unable to use document.write when extracting code from the internet

I am currently developing a game using emulatorjs and ruffle. The goal is to have it all contained in a single downloadable file that can be run locally. I attempted to create another file for auto-updating purposes, but encountered issues with some of the ...

Typescript: Potential null object error when defining a method

I recently encountered an error message stating "Object is possibly null" while working on the changePageSize method in book-store.component.html. It seems like I need to initialize the object within the class, but I'm not familiar with how to do that ...

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

Tips for adjusting the preferred view resolution for a seamless blend of GSP and JSON views

I'm currently managing a grails 3.3.8 application that utilizes the angularjs profile. Both the REST API and angularjs assets are integrated within the same grails application. At the moment, I am not looking to separate them into two distinct applic ...

Obtain the value of an element from a React UI Material component (e.g. ListItemText)

Incorporated an onClick() event where a function is invoked to retrieve and display the value of any clicked element within the HTML body in a web component. <div id="root" onclick="handleClick(event)"></div> This snippet o ...

Eliminate disparity in Woocommerce shopping cart

I have a pizza with various toppings. When the user selects "Add Toppings," they appear as drop-down options defaulted to "none." I want to hide the selected "none" options in the cart and checkout. Although I've successfully hidden them on the cart ...

sending properties to dynamically loaded components

I'm struggling with transferring props between children and parent components using Vue Routes. Within my Layout component, I have a wrapper DIV structured like this: <template> <div class="container" v-bind:class="cssClass ...

Managing errors that occur while handling JSON with AJAX by implementing a suitable backup plan

Imagine there is a user.json file stored on a web server that contains: { "name” : “ivana”, “age” : “27” } Now, I make a request to retrieve this JSON data using the following code: var user = $.ajax({ url: pathsample.com/user.js ...