What is a method to categorize an array of objects by the identical value of a specified key field without relying on any third-party libraries?

I have a collection of unorganized JavaScript objects with similar keys but potentially different values. For example:

const raw_data = {
   "sweets":[
      {
         "flavor":"chocolate",
         "product":"icecream",
         "price":3
      },
      {
         "flavor":"vanilla",
         "product":"icecream",
         "price":3
      },
      ...
   ]
}

I need to transform this data into a new organized object where the unique values from the flavor variable become keys, each holding an array of objects with matching flavor values. Here's an example of the desired output:

const cleaned_data = {
   "chocolate": [
     {
         "flavor":"chocolate",
         "product":"icecream",
         "price":3
      },
      ...
   ],
   "vanilla": [
     {
         "flavor":"vanilla",
         "product":"icecream",
         "price":3
      },
      ...
   ],
   ...
}

If anyone has a function that can achieve this transformation without using external libraries, please share!

Answer №1

Consider utilizing the reduce() method for this problem.

const data = [
  {
     "type":"apple",
     "food":"fruit",
     "cost":2
  },
  {
     "type":"banana",
     "food":"fruit",
     "cost":1
  },
  {
     "type":"apple",
     "food":"snack",
     "cost":3
  },
  {
     "type":"orange",
     "food":"fruit",
     "cost":2
  }
]

const categorizedData = data.reduce((collection, item) => {
  if ( !collection.hasOwnProperty(item.type) ) {
    collection[item.type] = [];
  }
  
  collection[item.type].push(item);
  
  return collection;
}, {});

console.log(categorizedData);

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

I am interested in utilizing a variable's value as an ID within a jQuery function

When working with jQuery, I often use a variable to store values. For example: var x = "ID1"; To utilize the value of this variable as an ID in my jQuery functions, I simply concatenate it as shown below: $('#' + ID1).val(); Thank you for you ...

Guide to building a JavaScript array and storing data from a separate array into the newly created array in JavaScript

Can you help me create a JavaScript array and save another array of data to be part of the newly created array in JavaScript? I attempted it using the code below. Code: var vvv=this.new_products.length-this.quote.lines.length; let mmm={}; if(v ...

Utilizing Array.from with a XPathResult: A Comprehensive Guide

In my sample document, I found 138 nodes with the tag td using querySelectorAll. Array.from(document.querySelectorAll('td')).length 138 However, when I tried to do the same using XPath, I did not get any result: Array.from(document.evaluate(". ...

Tips for directing user focus to a text field when they click on a disabled href link

I currently have a website where I need to disable href links for users with pending statuses. I want these users to fill in details and press a submit button before proceeding to other pages. How can I set it up so that when a user clicks on a disabled li ...

Enhance Your HTML Skills: Amplifying Table Display with Images

Recently, I utilized HTML to design a table. The Table Facts : In the first row, I included an appealing image. The second row contains several pieces of content. In continuation, I added a third row. The contents in this row are extensive, resulting i ...

Styling hyperlinks upon exporting an HTML table to Excel

I am trying to export an HTML table to Excel using JavaScript by following the instructions provided in Export HTML table to Excel its downloading table contents to the Excel. However, I have encountered an issue where one of the columns in my table conta ...

Instructions on including a directory in the package.json file for publication on npm

I am facing an issue when attempting to publish a module in the npm repository as it is not recognizing the 'lib' folder. Even though I have included it in the package.json file as shown below, the 'lib' folder contents are not being re ...

Table borders disappear when loading PHP echoed tables with jQuery and Ajax

Currently, I am delving into the world of jQuery, PHP, AJAX, and MySQL. My objective is to retrieve a table from the MySQL server and exhibit it on a webpage. This involves two PHP files – one serves as the back-end script connecting to the database and ...

Calculate the overall length of a specified time interval using Node Js

My task involves calculating overtime based on work start and end times. We are looking to calculate overtime hours that fall outside of the regular work schedule. For example, the regular work timings are from 10:00 AM to 07:00 PM Overtime needs to be ...

What is the best way to insert a value X following every minimum value in an array?

When I input an array, the code initially identifies the minimum values and then proceeds to add zeroes after each minimum value. For instance, if we have an array = 1,1,3,1,1, where the minimum value is 1, the desired output should be = 1,0,1,0,3,1,0,1, ...

What is the process of transferring information from one window to another window?

Is there a way to transfer data between two windows? In my parent window, I have a button that redirects to another page with a success button. When the success button is clicked on the child window, I want to display "success" text on the parent window. ...

Instructions for creating a scrollable unordered list when it reaches its maximum capacity

My HTML code has a <ul> element with the following structure: <ul id="messages"> </ul> In my HTML file, I have not specified any <li> items. However, in my JavaScript code using jQuery, I dynamically add <li> items to the & ...

Adding a new item to an array in J

What is the optimal approach to insert an element at a specific position in an array using J? I am struggling with passing three arguments to the verb I am trying to create. The basic idea of the code I intend to write goes like this: insert =. dyad : &a ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

Cannot transfer variables from asynchronous Node.js files to other Node.js files

Is there a way to export variable output to another Node.js file, even though the asynchronous nature of fs read function is causing issues? I seem to be stuck as I am only getting 'undefined' as the output. Can someone help me identify where I ...

Tips on reloading or refreshing a react-table component using my form component

I currently have two reactJS components set up: CustomerForm component, which includes a form along with form handling code. CustomerList component, which utilizes react-table to list the customers. Both components are fully functional and operational. ...

Utilizing various camera set-ups within Three.js

How can I smoothly switch between two different cameras in Three.js while transitioning from one to the other? Imagine a scene with a rock and a tree, each having its own dedicated camera setup. I'm looking for a way to seamlessly transition between ...

Is it possible to simultaneously configure `center` and `bounds` in Angular-google-maps without causing any conflicts or errors?

When using the ui-gmap-google-map, I've noticed that the center attributes can sometimes conflict with the bounds attributes. Unfortunately, the documentation doesn't specify which has higher priority if both are set. Imagine a situation where I ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

Using Vue.js to bind data in two directions by using an object with v-for

I can't seem to get input data properly bound to object properties. When I try to iterate through an object to create input fields based on its attributes, the v-model data binding doesn't seem to be working as expected. Even with the code below, ...