Mapping this particular array of objects to an array grouped by the shared key value requires a specific process. Let's explore how

Looking to transform this simplified array of objects:

var items = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"},  {"function":"function_2","process":"process_3"},  {"function":"function_2","process":"process_4"}]

into a new array based on the keys, resulting in:

result = [
{
    "function":"function_1",
    "process": [
      "process_1",
      "process_2" 
  ]
}, 
{
    "function":"function_2",
    "process": [
      "process_3",
      "process_4" 
  ]
}
]

Answer №1

For my dear friend

var data = [{"function":"function_1","process":"process_1"}, {"function":"function_1","process":"process_2"}, {"function":"function_1","process":"process_3"},  {"function":"function_2","process":"process_3"},  {"function":"function_2","process":"process_4"}]


var result = data.reduce( (a,b) => {
  
    var index = a.findIndex( x => x.function === b.function);
  
    return index === -1 ? a.push({ function : b.function, process : [b.process] }) : a[index].process.push(b.process), a;
  
}, []);


console.log(result)

Answer №2

const items = [{
  "function": "function_1",
  "process": "process_1"
}, {
  "function": "function_1",
  "process": "process_2"
}, {
  "function": "function_1",
  "process": "process_3"
}, {
  "function": "function_2",
  "process": "process_3"
}, {
  "function": "function_2",
  "process": "process_4"
}]

const uniqueFunctionList = [] // keeping track of unique function names
const resultArr = []          
items.forEach(item => {
  if (!uniqueFunctionList.includes(item.function)) {
    uniqueFunctionList.push(item.function)           
    let tmp_obj = {}
    tmp_obj['function'] = item.function              
    tmp_obj['process'] = [item.process]              
    resultArr.push(tmp_obj)                          
  } else {                                           
    resultArr.forEach(result => {                    
      if (result.function == item.function) {       
        result.process.push(item.process)            
      }
    })
  }
})

console.log(resultArr)

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

Arrangement of Bootstrap card components

Each card contains dynamic content fetched from the backend. <div *ngFor="let cardData of dataArray"> <div class="card-header"> <div [innerHtml]="cardData.headerContent"></div> </div> <d ...

Remove a file using Mongoose and Express by simply pressing a button

Trying to delete a connected account using Express and Mongoose. When the user clicks on a button (confirming their desire to delete their account), I want their account to be removed from my user's collection. HTML code snippet: <div class=" ...

What could be causing the failure of the JSON parse for dynamic link parameters?

I am currently attempting to pass parameters to a dynamic page within an Amplify/NextJS application. This is still a work in progress. My objective is to utilize the passed parameters to generate a basic page based on 4 parameters included in the URL invo ...

Obtain the Present Controller Identity within AngularJS

Currently, I am working on developing a directive that can create a grid dynamically. The code I have written functions properly but there is one limitation where I need to explicitly mention the controller name 'DemoCtrl'. I am wondering if ther ...

`Can I distribute configuration data to all components using a JavaScript file?`

My approach involves using config data to simultaneously affect the status of all components. I achieve this by importing the config object from the same JavaScript file and incorporating it into each component's data. It appears to work seamlessly, ...

Performing multiple asynchronous tasks using RxJS by running Array.prototype.map in parallel batches or queues

Imagine having an array of variables, such as: [Sasha, Misha, Caitlyn, ...String] (string[]) with a sizable length of about 10k elements. If you want to run an asynchronous parallel task with these elements, but not all at once like Promise.all, rather in ...

Tips for sending JSON data from JavaScript to PHP servers

After encoding an array into JSON using JavaScript, I set up my ajaxrequest object like this: var data = JSON.stringify(cVal); function ajaxRequest(url, method, data, asynch, responseHandler){ var request = new XMLHttpRequest(); request.open(meth ...

We encountered an issue while trying to bootstrap react with the './node_modules/bootstrap/dist/js/bootstrap.min.js' module. The error was a result of the module not being able

Error : I encountered a problem when trying to add a navbar using Bootstrap. Without importing the jQuery part, the navbar works but the collapsing feature does not work. However, when I add the jQuery part, I receive the following error: ./node_modules ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

Unable to Transmit Authorization Header in Cross-Domain Access Situation

My Node.js server has cross-origin communication enabled, allowing my Vue application to access its API from a different origin where static assets are served. This is achieved by setting the following code in Node.js: res.setHeader('Access-Control-Al ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

Using Bootstrap Collapse with EJS Iteration

I am having trouble with this specific section of my ejs file where the collapse feature is not functioning correctly. Can someone please assist me? <% for(var i=0;i<data.length;i++){%> <div id="content"> <p><%=data[i].w ...

Is there a performance benefit to using node.js over client-side JavaScript in comparison to Chrome/V8?

Currently, I am working on a client-side javascript application for image manipulation. However, some of the operations are running quite slowly in the browser, taking about 2-3 seconds to complete. To address this issue, I am considering implementing a s ...

Is it possible to set an onmousedown event to represent the value stored at a specific index in an array, rather than the entire array call?

Apologies if the question title is a bit unclear, but I'm struggling to articulate my issue. The challenge lies in this synchronous ajax call I have (designed to retrieve json file contents). $.ajax({ url: "/JsonControl/Events.json", dataTyp ...

Enhancing IntelliJ IDEA's autocomplete functionality with JavaScript libraries

Is there a way to add my custom JavaScript library to IntelliJ IDEA 10.5 or 11 for autocomplete functionality? I want to specify that IDEA should recognize and suggest auto-completions for objects from my library. While it sometimes works automatically, ...

An AngularJS directive designed to execute after a text input has been modified

I have integrated a bootstrap calendar datepicker that interacts with and updates an <input type="text"> field. As of now, when I use ng-change="myAngularExpression()", the function gets executed the moment the text box is selected. Is there a way t ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

The reason why JavaScript doesn't treat "1-1" as 0 in an operation like it does with "123" to 123 during calculations

When dealing with JavaScript, the difference between "123" and "1-2" can be confusing. While "123" is recognized as a string type with a numerical value, "1-2" is also a string type but it does not allow for multiplication. Why doesn't JavaScript hand ...