Combining and grouping objects by their IDs in a JavaScript array

Information:

[
  {
    "id": "ewq123",
    "name": "Joshua",
    "order": "Pizza"
  },
  {
    "id": "ewq123",
    "name": "Joshua",
    "order": "Burger"
  },
  {
    "id": "a512dsa",
    "name": "Eugene",
    "order": "Pizza"
  },
]

Desired outcome:

[
 {
   "id": "ewq123",
   "name": "Joshua",
   "order": ["Burger", "Pizza"]
 },
 {
   "id": ""a512dsa",
   "name": "Eugene",
   "order": "Pizza"
 },
]

Are there more efficient ways to achieve this using ES6 functions, such as the spread operator?

Answer №1

Use the following code snippet to achieve a similar result:

var mainArray = [{
        "id": "ewq123",
        "name": "Joshua",
        "order": "Pizza"
    },
    {
        "id": "ewq123",
        "name": "Joshua",
        "order": "Burger"
    },
    {
        "id": "a512dsa",
        "name": "Eugene",
        "order": "Pizza"
    },
];
var newHashmap = mainArray.reduce((objects, item) => {

    if (objects[item.id]) {
        objects[item.id].order.push(item.order)
    } else {
        item.order = [item.order]
        objects[item.id] = {
            ...item
        }
    }
    return objects;
}, {});

var updatedArray = Object.values(newHashmap);

console.log(updatedArray);

Output :

[
 {
   "id": "ewq123",
   "name": "Joshua",
   "order"     : ["Burger", "Pizza"]
 },
 {
   "id": "a512dsa",
   "name": "Eugene",
   "order": "Pizza"
 },
]

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

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Tips for guiding users to a different page based on whether a linkid is associated with a specific Cat

I created this script, but I am facing an issue with the redirect. Can someone please assist me as soon as possible? <?php include('config.php'); $number = intval($_POST['catid']); $query = mysql_query("SELECT * FROM sound ...

Utilizing an Observable in an Angular 6 service to ensure proper synchronization with Okta token present in local storage

Within my application, I have implemented third-party authentication to facilitate user login and store a token in their local storage. To enhance the user experience, I am developing a service to cache profile information. This service utilizes the user&a ...

Create a cookie on a subdomain that is accessible by all other subdomains

I have been working on a NextJS project that involves multiple apps on separate subdomains. My objective is to enable single sign-on so that when I log in to one app, I am automatically signed in to all the others. We are utilizing nookies as our cookie ha ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...

jQuery must provide the complete object rather than just the data within it

What is the best way to retrieve the entire <div class="loan_officer_apply_now_link"><a href="">APPLY NOW!</a></div> At present, only the "a" element content is being returned <a href="">APPLY NOW!</a> Test Code $( ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

Creating a custom JavaScript function to manipulate arrays

I am working on a project involving an array of strings that represent class names. My goal is to instantiate these classes using their string names, but so far my attempts with the window object have been unsuccessful. The array structure looks like this ...

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Mapping fields in Spring to JSON can be tricky, especially when dealing with fields that can be

In my object, there is a String value field which can contain either true or false. The issue arises when Spring/Jackson maps this to value: "true" as a String, causing problems with certain angularjs ng-model mappings that expect a boolean. Is there a way ...

Requesting data with Ajax: utilizing parameters in the format of x-www-form-urlencoded

When adding parameters to a get/post request, it is important to encode them in application/x-www-form-urlencoded form. Is it necessary to encode values each time? Does JavaScript provide a method for encoding values? What options are available for caching ...

Retrieving external response data within a nested $http request

Excuse me as I am new to working with AngularJS. I am trying to figure out how to properly handle a nested $http call in my code, $http({ method: 'GET', url: host1, params: { 'format': 'json', } }).then(function ...

Discover the magic of observing prop changes in Vue Composition API / Vue 3!

Exploring the Vue Composition API RFC Reference site, it's easy to find various uses of the watch module, but there is a lack of examples on how to watch component props. This crucial information is not highlighted on the main page of Vue Composition ...

Is it possible to extract information from a string with regular expressions?

As I sift through a myriad of arbitrary "Header" data in node. Here's an example of what it looks like: _Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP= ...

I'm curious about what exactly happens when the NextJS Link component is triggered and how we can effectively capture and respond

As I was developing a simple navbar that uses a JSON data to dynamically generate its links, I encountered the need to visually persist the active link/route. To achieve this, I experimented with two different implementations: Initial approach: In the Me ...

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

Enhancing functionality through the press of a button

I wrote a script that, upon button click, finds the closest location to your current position by searching through an array. It then locates the corresponding entry in another array and adds a number to that entry. However, I encountered a problem with app ...

Creating a Javascript countdown timer that does not involve displaying the

I stumbled upon this code on a website, but there's one tweak I'd like to make. Unfortunately, I can't seem to figure it out myself, so I'm reaching out for some help. What I want to achieve is removing the year from the date so that th ...