transform json array into a consolidated array by merging identical IDs

I need to transform an array into a different format based on the values of the ID and class properties.

Here is the initial array:

const json = [{
  "ID": 10,
  "Sum": 860,
  "class": "K",
}, {
  "ID": 10,
  "Sum": 760,
  "class": "one",
}, {
  "ID": 10,
  "Sum": 860,
  "class": "two",
}];

The desired output should look like this:

[{"ID":10,"K":860,"one":760,"two":860}]

Answer №1

Perhaps there is a more efficient solution out there, but I managed to whip this up in just 5 minutes.

const input = [
{
    "ID": 10,
    "Sum": 860,
    "class": "K",
},
{
    "ID": 10,
    "Sum": 760,
    "class": "one",
},
{
    "ID": 10,
    "Sum": 860,
    "class": "two",
}];

const result = [];

input.forEach(item => {
  const exists = result.find(i => i.id === item.id);
  if (exists) {
    exists[item.class] = item.Sum;
  } else {
    item[item.class] = item.Sum;
    delete item.Sum;
    delete item.class;
    result.push(item);
  }
});

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

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

JavaScript MP3 player

Could someone kindly point out where I went wrong? I am attempting to create an MP3 player using CSS, HTML, and JavaScript. Currently, the script only functions to start or stop the audio file. However, I keep encountering an error message: TypeError: docu ...

The default value for an input of type date should be set to the current date

I am working on a project that involves an input field with the type of "date". I have implemented Materialize to provide a user-friendly date picker. My goal is to set the default value of this input field to the current date when it is initialized. Here ...

Reposition the Column, Filter popover within the MUI Data Grid Pro

I am working with the MUI Data Grid Pro to showcase my data. By default, the Data Grid Pro exhibits the toolbar on the left side. Although I managed to shift the toolbar to the right side, the popovers and menus retained their position on the left. My inte ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...

The data source is having trouble connecting to the updated JSON format due to issues with pagination

I'm utilizing pagination.js to fetch asynchronous data using the code below. $('#demo').pagination({ dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?&ap ...

How can HtmlUnit be used to identify and address website pages that display errors?

I've encountered an issue while trying to access this Ajax page through my Java program using the HtmlUnit 2.15 API. It seems that the problem arises from a broken link to a missing file located here. This is the snippet of code I'm working with ...

Router DOM in conjunction with Next.js

I am attempting to extract the output of the code in navigation, but unfortunately it is generating a dreadful error: Unhandled Runtime Error Error: You cannot render a <Router> inside another <Router>. You should never have more than one in ...

Loading Three.js JSON files in Apache server

I have developed a website showcasing 3D models using JSON files with three.js. Everything works fine when I open the HTML file from my local computer. However, when I upload all the files to my Apache webserver, nothing is displayed. I attempted to run ...

Is it possible to include a border/stroke on a Raphael picture?

Currently, I am attempting to enhance a Raphael image element by adding either a border, stroke, or drop shadow. My end goal is to create an animated glowing border effect. Previously, I successfully implemented this on traditional HTML elements using Java ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

JavaScript - unable to view updated information without refreshing page

I am currently developing a Single Page Application (SPA) using Rails for the backend and JavaScript for the frontend. When I submit the initial form to create a Resource, it shows up on the page immediately upon pressing the submit button. However, when I ...

Determining the return type of a function by analyzing its parameters

Let's consider the following scenario: export function bar(bar?: string) { return bar ? { bar } : {}; } const B1 = bar(); const B2 = bar("z"); Upon compilation, the types inferred for both B1 and B2 are: { bar: string; } | { bar? ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Is there a way in React JS to attempt a function multiple times using try/catch?

I wrote a function with try catch inside where I make a call to an API for a response. The response returns a Result object with some data. Occasionally, I need to retry the function if certain conditions are met, such as having no name but having a bundle ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

recover the identifier from the cryptic hash reply

Is it possible to decrypt the ID from the encrypted hash response in a Java Android function? I am facing an issue where I am unable to retrieve the ID when I take the username string instead of the result string displayed as a toast message. This is caus ...

Is it possible to set data using a React Hooks' setter before the component is rendered?

Instead of making a real API call, I am exporting a JS object named Products to this file to use as mock data during the development and testing phase. My goal is to assign the state of the function to this object, but modified with mapping. The current st ...

"Exploring the interactivity of touch events on JavaScript

Hi there, I'm currently facing an issue with the touch events on my canvas. While the mouse events are functioning correctly and drawing as expected, incorporating touch events seems to be causing a problem. When I touch the canvas, the output remains ...

Encountering a duplication issue when redirecting components in Angular2/TypeScript using navigateByUrl

Seeking guidance on implementing the login function where the current component redirects to another one upon clicking the login button. Below are my .ts and .html files: login.component.ts login.component.html The issue arises when using npm start for ...