Combining objects within an array based on shared key values

Is there a way to merge objects with the same date into one cohesive data set? I could use some guidance.

const info = [
                { date: '1 Day', green: 35 },
                { date: '2 Day', green: 64 },
                { date: '3 Day', green: 46 },
                { date: '4 Day', green: 87 },
                { date: '5 Day', green: 32 },
                { date: '1 Day', red: 85 },
                { date: '2 Day', red: 55 },
                { date: '3 Day', red: 37 },
                { date: '1 Day', orange: 4 },
                { date: '2 Day', orange: 44 },
                { date: '3 Day', orange: 9 },
                { date: '4 Day', orange: 88 },
                { date: '5 Day', orange: 60 },
                { date: '6 Day', orange: 15 },
            ];

Ideally, the output should look like this:

const info = [
                { date: '1 Day', green: 35, red: 85,  orange: 4 },
                { date: '2 Day', green: 64, red: 55,  orange: 44 },
                { date: '3 Day', green: 46, red: 37, orange: 9  },
                { date: '4 Day', green: 87, orange: 88 },
                { date: '5 Day', green: 32, orange: 60 },
                { date: '6 Day', orange: 15 },
            ]

Answer №1

To efficiently combine objects with the same key (in this case, date), you can utilize a hash and the spread operator within an array iteration.

// Function to merge object arrays based on a specific property
// `key` - <String>; property name used to group objects
// `data` - <Array>, containing objects to be merged
function mergeObjectArrays(key, data) {
   const hash = []
   for (let el of data) {
      const keyValue= el[key]
      hash[keyValue] = { ...(hash[keyValue] || {} ), ...el }
   }

   return Object.values(hash)
}

// Sample dataset
const data = [
    { date: '1 Day', green: 35, red: 85,  orange: 4 },
    { date: '2 Day', green: 64, red: 55,  orange: 44 },
    { date: '3 Day', green: 46, red: 37, orange: 9  },
    { date: '4 Day', green: 87, orange: 88 },
    { date: '5 Day', green: 32, orange: 60 },
    { date: '6 Day', orange: 15 },
]

const result = mergeObjectArrays('date', data)
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

Is there a way to modify this query so that it only retrieves items containing a specific value within its subarray?

I am attempting to customize a voting script (Thumbsup) and I require this query to only retrieve array items with 'cat' => '1' in the subarray. <?php $items = ThumbsUp::items()->get() ?> Here is an example of the live gen ...

Adjusting value of one input field according to the content of another text field in an

Just starting out with Angular and I am looking to dynamically change the value of a hidden input field called 'cc_card' based on the first digit entered in another input field called 'cc_number'. For example, if the user enters 5 in &a ...

Having issues with the script not functioning when placed in an HTML document or saved as a .js file

Even though the database insertion is working, my script doesn't seem to be functioning properly. The message "successfully inserted" appears on the saveclient.php page instead of the index.html. In my script (member_script.js), I have placed this in ...

Displaying a Collection of Strings Using PHP and MySQL

I am facing a challenge when it comes to displaying a list of strings from a MySQL server using PHP. I would like the list to have the following format: Name 1 Name 2 Name 3 Name 4 Each name should be in a separate cell, but I'm unsure about how to ...

The code within $(document).ready() isn't fully prepared

Feeling frustrated after spending hours searching and attempting to refactor one of my old modules on a rendered Mustache template. It's like diving into code chaos. <section id="slideShow"> <script id="slideShow-template" type="text/tem ...

How can I use Node.js Express to upload files with Multer?

I am facing an issue while trying to upload a file image using multer in express. The file gets successfully uploaded to the directory, but the name of the file is not being saved in the database. I am utilizing mongodb with express and currently, the file ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

The alignment of elements in the div seems to be slightly skewed

Currently, I am in the process of creating a website with the temporary name yeet.io. I am facing an issue where I am attempting to center both an input and h1 element inside a div vertically and horizontally, but they keep appearing misaligned for some r ...

Variations in output observed from angular function across various sections within DOM

After fetching a list of permissions in the background, my goal is to display a page or an error message based on whether the user has the required permissions. I encountered an unusual issue where both sections of the page are being displayed despite hav ...

Ways to merge several getServerSideProps functions

Within my project, I have two important pages: index.js and other.js. In index.js, there exists a crucial method known as getServerSideProps: export async function getServerSideProps(context) { //code here } The challenge arises when I realize that I ...

Transforming a mathematical expression stored as a string into an array

Is there a simpler way to convert a String like 1+40.2+(2) into a String array [1, +, 40.2, +, (, 2, )] for a Shunting Yard algorithm in my Calculator class? Due to input being entered without spaces, input.split("\\s+") won't work. I' ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Retrieving an AJAX array POST in Laravel 5 Controller

Below is the structure of my form: <td> <input type="text" name='name[]' class="form-control"/> </td> <td> <input type="text" name='mail[]' class="form-control"/> </td> <td> <select na ...

Setting up the react-ultimate-pagination component

I've been experimenting with the react-ultimate-pagination package available at: https://github.com/ultimate-pagination/react-ultimate-pagination My goal is to configure it in a way similar to their basic demo showcased here: https://codepen.io/dmytr ...

jQuery plugin is not effectively targeting the directive

Recently, I have been experimenting with using a sleek jQuery datepicker and decided to turn it into a directive for my angular app. The implementation of the directive is currently very straightforward: directive('datePicker', function() { ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...