Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below:

[{
    "groupid": 29,
    "percentage": 14
}, {
    "groupid": 29,
    "percentage": 22
}, {
    "groupid": 59,
    "percentage": 66,
}]

I am looking to convert it into the format shown below using JavaScript.

{
    "29": [14, 22],
    "59": [66]
}

Answer №1

Transform the data into an object structure. For each element in the input array, check if there is an array at the specified groupid. If not, create a new array and add the value:

const inputData = [{
    "groupid": 29,
    "percentage": 14
}, {
    "groupid": 29,
    "percentage": 22
}, {
    "groupid": 59,
    "percentage": 66,
}];
const outputData = inputData.reduce((accumulator, { groupid, percentage }) => {
  if (!accumulator[groupid]) accumulator[groupid] = [];
  accumulator[groupid].push(percentage);
  return accumulator;
}, {});
console.log(outputData);

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

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

Trouble with Adding and Showing Arrays

function resetValues() { var p = parseFloat($("#IA").val()); var q = parseFloat($("#IB").val()); var m = parseFloat($("#CGCD").val()); var aR = []; aR.push("GCD(" + p + "," + q + ")=" + m); document.getElementById("PGCD").innerHTM ...

WSO2 does not accept the use of the '@' symbol as an input parameter in its methods

Every time I try to input an @ symbol, instead of the expected empty list of roles, I get an error. The function in question is roles(), with the input parameter being the last part of the URL. I specifically need to use the @ symbol as I intend to use ema ...

Attempting to trigger the timer to begin counting down upon accessing the webpage

Take a look at this example I put together in a fiddle: https://jsfiddle.net/r5yj99bs/1/ I'm aiming to kickstart as soon as the page loads, while still providing the option to pause/resume. Is there a way to show the remaining time as '5 minute ...

What is the best way to extract a specific year and month from a date in a datatable using

My dataset includes performance scores of employees across various construction sites. For instance, on 2020-03-15, ALI TAHIRI was at the IHJAMN site. I need to filter this dataset by year and month. If I input 2020 for the year and 03 for the month, the d ...

Enhancing vanilla HTML elements with custom props using React

const handleSelectChange = (e) => { console.log(e.target.getAttribute('id')); }; return ( <div> <select onChange={(e) => handleSelectChange(e)}> <option value="1-10" id=&qu ...

React - Implementing toggling of a field within a Component Slot

I find myself in a peculiar situation. I am working on a component that contains a slot. Within this slot, there needs to be an input field for a name. Initially, the input field should be disabled until a web request is made within the component. Upon com ...

Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible ...

Generating pop-up upon loading with CSS3

I have searched through numerous threads and forums in the hopes of finding a solution, but I haven't been successful. My issue lies with triggering a popup on my website. I followed online tutorials to create a popup window, which I was able to do su ...

Using Node.js to showcase MySQL data in an HTML table

Currently, I am in the process of learning how to utilize node.js with mysql. Despite my efforts to search for comprehensive documentation, I have not been successful. I have managed to display my mysql data on my browser, but ultimately I aim to manage it ...

Struggling with incorporating a web link into a structured data table

I am currently working on a Django application that utilizes jQuery DataTables to display a list view of items. My goal is to include a hyperlink in the first element of the table, which represents the primary key for the model being displayed. This link s ...

Decoding JSON using Retrofit - structured data model

There was an error encountered: An exception of 'java.lang.NullPointerException' was thrown. Unable to evaluate pl.netizens.eonbeacon.storage.EonBeaconModel.toString() I attempted to parse JSON using retrofit. I received JSON data from the s ...

Pressing the Add button will create a brand new Textarea

Is it possible for the "Add" button to create a new textarea in the form? I've been searching all day but haven't found any logic to make the "Add" function that generates a new textarea. h1,h2,h3,h4,h5,p,table {font-family: Calibri;} .content ...

What could be causing the malfunction in the cloning of the carousel item?

My goal was to create a carousel that displays multiple images in one slide. However, I encountered an issue where once the fourth image is reached, the other three images are forcibly hidden. I want to give credit to the original creator of this code snip ...

Utilizing string to access property

Is there a better way to access interface/class properties using strings? Consider the following interface: interface Type { nestedProperty: { a: number b: number } } I want to set nested properties using array iteration: let myType: Type = ...

Is it feasible to obtain the userId or userInfo from the Firebase authentication API without requiring a login?

Is it feasible to retrieve the user id from Firebase authentication API "email/password method" without logging in? Imagine a function that takes an email as a parameter and returns the firebase userId. getId(email){ //this is just an example return t ...

My goal is to use both jQuery and PHP to automatically populate the dropdown list

Here is my PHP code for executing a query: $host = "localhost"; $user = "root"; $pass = "abc123"; $databaseName = "class"; $con = mysql_connect($host,$user,$pass); $dbs = mysql_select_db($databaseName, $con); $result = mysql_qu ...

Using Newtonsoft.JSON in C# to serialize and deserialize an array of objects

I'm struggling to figure out how to serialize and deserialize an array of objects that implement an interface using Newtonsoft.JSON. Let's take a look at a simple example: public interface IAnimal { public int NumLegs { get; set; } //etc.. } ...

Challenges regarding OAuth2 and the angular-auth2-oidc Library - Utilizing PKCE Code Flow

As a newcomer to OAuth2 and the angular-auth2-oidc library, I may make some beginner mistakes, so please bear with me. MY GOAL: I aim to have a user click on the login link on the home page, be directed to the provider's site to log in, and then retu ...

Is there a way to access an SD card by clicking on an HTML link using JavaScript?

UPDATE: I am seeking a way to embed an HTML file with JavaScript or jQuery that can directly access the contents of the SD card while being opened in a browser. Currently, I have posted code for accessing it through an activity, but I want to be able to d ...