Efficient ways to organize JSON objects using JavaScript

I am in need of restructuring the data retrieved from an API call, which currently looks like this:

{
  "Label3":
    [
      { "name": "superman", "power": 8900 },
      { "name": "iron man", "power": 3000 },
      { "name": "spike spiegal", "power": 200 },
      { "name": "doctor strange", "power": 800 }
    ],
  "Label18":
    [
      { "name": "goku", "power": 9000 },
      { "name": "vegeta", "power": 8500 },
      { "name": "pringles can", "power": 1 }
    ],
  "Label37":
    [
      { "name": "dr manhattan", "power": 100000 },
      { "name": "mayonaise", "power": 10 }
    ]
}

My goal is to extract the highest power value from each array and reorganize the structure to look like this:

{
    "groupName": 'Label3',
    "highestPower": 8900,
    "heroes": [
        {"name":"superman","power":8900},
        {"name":"iron man","power":3000},
        {"name":"spike spiegal","power":200},
        {"name":"doctor strange","power":800}
    ],
},
{
    "groupName": 'Label18',
    "highestPower": 9000,
    "heroes": [
        {"name":"goku","power":9000},
        {"name":"vegeta","power":8500},
        {"name":"pringles can","power":1}
    ],
},
{
    "groupName": 'Label37',
    "highestPower": 100000,
    "heroes": [
        {"name":"dr manhattan","power":100000},
        {"name":"mayonaise","power":10}
    ],
}

I have been considering using a forEach loop on each array element to find the maximum value and assign it to a variable for comparison. However, I am unsure how to proceed with restructuring the data as required.

Answer №1

You can retrieve the entries and construct a new object with the desired properties.

var data = { Label3: [{ name: "superman", power: 8900 }, { name: "iron man", power: 3000 }, { name: "spike spiegal", power: 200 }, { name: "doctor strange", power: 800 }], Label18: [{ name: "goku", power: 9000 }, { name: "vegeta", power: 8500 }, { name: "pringles can", power: 1 }], Label37: [{ name: "dr manhattan", power: 100000 }, { name: "mayonaise", power: 10 }] },
    result = Object
        .entries(data)
        .map(([groupName, heroes]) => ({
            groupName,
            highestPower: heroes.reduce((max, { power }) => Math.max(max, power), -Infinity),
            heroes
        }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To loop through the labels and find the highest power, you can utilize Object.keys() along with Array.reduce like this:

var attributes = {
  "Attribute5":
    [
      { "name": "batman", "power": 7000 },
      { "name": "wonder woman", "power": 5000 },
      { "name": "hulk", "power": 6000 }
    ],
  "Attribute13":
    [
      { "name": "flash", "power": 8000 },
      { "name": "thor", "power": 7500 },
      { "name": "black widow", "power": 4500 }
    ],
  "Attribute21":
    [
      { "name": "cyborg", "power": 4000 },
      { "name": "catwoman", "power": 3000 }
    ]
}

var groupedAttributes = Object.keys(attributes).map((key) => {
  return {
    category: key,
    maxPower: attributes[key].reduce(( total, current ) => Math.max( total, current.power ), 0),
    characters: attributes[key]
  }
});

console.log(groupedAttributes);

Answer №3

Assuming the source data is already sorted:

var src = getSortedData();
var dst = [];
for(var i in src) {
    dst.push({
        "groupName":i,
        "highestPower":src[i][0].power,
        "heroes":src[i]
    });
}
console.log( JSON.stringify(dst,null,2) );

function getSortedData() {
    return {
    "Label3":
      [
        { "name": "superman", "power": 8900 },
        { "name": "iron man", "power": 3000 },
        { "name": "spike spiegal", "power": 200 },
        { "name": "doctor strange", "power": 800 }
      ],
    "Label18":
      [
        { "name": "goku", "power": 9000 },
        { "name": "vegeta", "power": 8500 },
        { "name": "pringles can", "power": 1 }
      ],
    "Label37":
      [
        { "name": "dr manhattan", "power": 100000 },
        { "name": "mayonaise", "power": 10 }
      ]
  };
}

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

Broadcasting events across the entire system

I'm trying to accomplish something specific in Angular2 - emitting a custom event globally and having multiple components listen to it, not just following the parent-child pattern. Within my event source component, I have: export class EventSourceCo ...

Exploring the concept of making nested API requests within a route using Node.js and

Being a newbie in the world of coding, I'm excited to make my first post here. My current learning project involves developing a website that utilizes an external CRM for storing client data received from web forms. The storage functionality is up an ...

Unable to capture screenshot of hovered element using Cypress

Having an issue with taking a screenshot of an element with a hover effect. The screenshots always come out without the hover effect applied. tableListMaps.lineWithText('Hello world', 'myLine'); cy.get('@myLine').realH ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

How can I remove the popover parents when clicking the confirm button using jQuery?

I am having trouble sending an AJAX request and removing the parent of a popover after the request is successful. I can't seem to access the parent of the popover in order to remove it, which is causing me some frustration. // Code for deleting w ...

Using jQuery AJAX to Redirect to a 404 Page in Case the Load Method Encounters Failure

My website utilizes AJAX to load all pages using the jQuery load method. I modified this tutorial to work with Wordpress. The issue I am facing now is that when the load method encounters an error (such as a 404 due to a broken link), the AJAX transition ...

Unusual behavior observed within for loop; code within not running as expected

I will be presenting my code along with some images to illustrate the issue at hand. Something as simple as declaring a variable or using the log function results in the json being undefined. Upon entering text into the input field, the ajax call is trigg ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

A deep-dive into using recursive queries in Postgres with json data types

Presently, the table consists of two columns - one with type as an integer and another with type as JSON data. The JSON content within the table is unstructured, allowing for any level of nesting. Each JSON document can be categorized as either a parent o ...

The Glyphicon icon fails to appear on the initial page load and only shows up after refreshing the

I have been utilizing bootstrap.min.css from bootstrap v3.3.5 which I downloaded from http://getbootstrap.com and used it locally. However, I encountered an issue with glyphicons when running it on IE 9 and above. The glyphicon icon disappears on the first ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

Is there a way to position the menu above the button?

I need some help with my menu. Currently, it is showing up below the button and within my footer instead of above the content like I want it to. If anyone can assist me in understanding what I am doing wrong, I would greatly appreciate it. Thank you for ta ...

Converting numerical data from JSON to a structured model

I am attempting to extract JSON data from a web service provider and integrate it into my web service client. My current approach involves using the GSON library, but I have encountered an issue due to the structure of the JSON data: { "aaData": [ { ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

MVC5 Toggle Button for Instant Display and Concealment

I used to utilize this method in Web Form development by targeting the id and name of the input radio button. However, I am encountering difficulties implementing it in MVC5. Can someone kindly point out where I might be going wrong? Upon selecting a radi ...

Looking to organize my divs by data attributes when clicked - how can I achieve this with javascript?

I am looking to implement a dropdown sorting functionality for multiple divs based on different data attributes such as price and popularity. The specific divs are labeled as "element-1" and are contained within the "board-container". var divList = $(". ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...