Obtain the Key with the Greatest Value from a JSON Object

I'm currently working with data fetched from an API response in an attempt to identify the pitch with the highest speed. Below is a snippet from the API response.

{
page: 1,
total_pages: 4,
listings: [
    {
        name: "Zack Greinke",
        pitches: [
            {
                name: "Slider",
                speed: 88,
                control: 79,
            },
            {
                name: "Curveball",
                speed: 77,
                control: 67,
            },
            {
                name: "Fastball",
                speed: 95,
                control: 82,
            }
        ]
    },
    {
        name: "Max Scherzer",
        pitches: [
            {
                name: "Changeup",
                speed: 84,
                control: 76,
            },
            {
                name: "Sinker",
                speed: 92,
                control: 80,
            }
        ]
    },
]
}

Here's my approach:

itemSet.forEach( (item) => {
    let fastestPitch = Object.keys(item.pitches).reduce((a, b) => {
        item.pitches[a] > item.pitches[b] ? item.pitches[a].name : item.pitches[b].name
     });
});

However, this method consistently returns the name of the last pitch listed. My goal is to fetch the pitch with the highest speed.

Update: I also attempted the following solution, but encountered an error message.

itemSet.forEach( (item) => {
    let fastestPitch = Object.keys(item.pitches).reduce((a, b) => {
        item.pitches[a].speed > item.pitches[b].speed ? item.pitches[a].name : item.pitches[b].name
     });
});

Error Encountered:

(node:80698) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'speed' of undefined

Answer №1

If you want to achieve a similar result, try following this approach:

const playersData = {
  page: 1,
  total_pages: 4,
  players: [{
      name: "Michael Jordan",
      stats: [{
          type: "Points per Game",
          value: 30.1,
        },
        {
          type: "Assists per Game",
          value: 5.3,
        },
        {
          type: "Rebounds per Game",
          value: 6.2,
        }
      ]
    },
    {
      name: "LeBron James",
      stats: [{
          type: "Points per Game",
          value: 27.0,
        },
        {
          type: "Assists per Game",
          value: 7.4,
        },
        {
          type: "Rebounds per Game",
          value: 7.4,
        }
      ]
    },
  ]
}

const highestScorers = playersData.players.map(({ stats }) => {
  return stats.reduce((a, c) => c.value > a.value ? c : a).type;
});

console.log(highestScorers);

Answer №2

To find the quickest pitch from each player, you can utilize the Array#map method on the entries in listings and then apply the Array#reduce method to determine the fastest pitches in pitches like so:

let data = { page: 1, total_pages: 4, listings: [{ name: "A.J. Burnett", pitches: [{ name: "4 Seam FB", speed: 96, control: 84, }, { name: "Knuckle Curve", speed: 79, control: 74, }, { name: "Sinker", speed: 95, control: 64, }, { name: "Changeup", speed: 81, control: 44, } ] }, { name: "Joe Smitch", pitches: [{ name: "4 Seam FB", speed: 91, control: 82, }, { name: "Changeup", speed: 69, control: 44, } ] }, ] };

let fastestPitches = data.listings.map(obj => {
  return obj.pitches.reduce((best, current) => {
    return best.speed > current.speed ? best : current
  }, {}).name
});

console.log(fastestPitches)

It's important to note that during the reduction process, the first argument (best, in this case) represents the output of the previous callback iteration. If you only return the name, you won't have access to the speed information. Therefore, by comparing speeds and returning the complete object with better attributes, you ultimately retrieve the name of the fastest pitch.

Answer №3

One possible approach is to implement a dynamic function that can traverse nested objects to find and return the object with the highest desired property value.

function getHighestValue(object, key) {
    return Object.values(object).reduce((result, obj) => {
        if (!obj || typeof obj !== 'object') return result;
        if (key in obj && (!result || result[key] < obj[key])) return obj;
        var temp = getHighestValue(obj, key);
        if (temp && (!result || result[key] < temp[key])) return temp;
        return result;
    }, undefined);
}

var data = { page: 1, total_pages: 4, listings: [{ name: "A.J. Burnett", pitches: [{ name: "4 Seam FB", speed: 96, control: 84 }, { name: "Knuckle Curve", speed: 79, control: 74 }, { name: "Sinker", speed: 95, control: 64 }, { name: "Changeup", speed: 81, control: 44 }] }, { name: "Joe Smitch", pitches: [{ name: "4 Seam FB", speed: 91, control: 82 }, { name: "Changeup", speed: 69, control: 44 }] }] },
    highestValue = getHighestValue(data, 'speed');

console.log(highestValue.name);
console.log(highestValue);

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

Converting a string into a regular expression using JavaScript

I am attempting to change the color of a text element when specific variations of the word "hello" are entered into an input field. While this works with a regular string comparison, it fails when using a regular expression. <input id="input" type="inp ...

The issue arises due to conflicting indent configurations between eslint and @typescript-eslint/indent

Currently, I am using eslint and prettier in a TS express application. I am trying to set the tab width to 4, but it appears that there is a conflict between the base eslint configuration and the typescript eslint. When looking at the same line, this is w ...

Attempting to remove certain characters from a given string

let currentDate = new Date(); currentDate.toLocaleString; If I were to console log the value of currentDate, it would show: Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time) However, what if I only want to display the minutes and seconds like 57: ...

Issue with Angular ui-select causing repeated $http requests in ui-select-choices

I'm currently working on integrating ui-select into my project, and this time I need to pass a controller function as options to ui-select-choices. Here's how it's set up: HTML: <ui-select ng-model="selectedItem" theme="selectize" ng-di ...

Effortlessly switch between CSS animation styles while adjusting animation settings

My HTML element with animation is defined as follows: <div id="box"></div> The box starts by moving 200 pixels to the right, taking 4 seconds to complete. .anim { animation-name: anim; animation-duration: 4s; animation-t ...

Converting a stringified array object to an object using Expressjs

When working with Angular, I am sending stringified data using FormData. Here is an example: this.formData.append('data', JSON.stringify(this.collections)) Now my challenge is converting this string back to an object in my Express backend. The d ...

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

Converting a JSON object to a JSON array can sometimes be challenging during JSON parsing

I'm attempting to convert a JSON String into an array by using the code snippet below: try { String holder = getJSONString(getApplicationContext()); JSONArray JSONARR= new JSONArray(holder); List<datatemp> dataList = new ArrayList& ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Navigating a vast JSON dataset containing identical key names: A step-by-step guide

I am faced with a massive json file that has the following format: name: 'xxx', worth: [123, 456, 789] children: [ {name: 'xxx', worth: [987, 654, 321], children: [ {name: 'xxx', ...

Struggling to get the hang of CSS animation?

Here is a code snippet that I am using: //Code for animating skills on view document.addEventListener("DOMContentLoaded", function(event) { function callback(observations, observer) { observations.forEach(observation => { if (observati ...

What steps can be taken to successfully import a JavaScript module without encountering a ReferenceError?

Recently, I created a Javascript export file with the following content: export const A = 1; export const B = 2; export const C = 3; As an experiment, I attempted to import this file into another Javascript document like so: import 'path/export_file. ...

The PHP equivalent of converting data to a JSON string, similar to the

When working with PHP's json_encode($array), I've noticed that diacritics can sometimes get messed up. However, if I update my database column to type text and pass javascript-created JSON over HTTP, everything appears fine. The issue arises when ...

The Highcharts download feature is not available when the title is removed

After setting the title of my chart to null, I noticed that I am no longer able to access the download menu on the chart. Check out this example for reference: http://jsfiddle.net/JVNjs/954/ var chart = new Highcharts.Chart({ chart: { renderT ...

divide an array into two separate arrays depending on whether the index position is odd or even

Here is an example array: Arr1 = [1,1,2,2,3,8,4,6]. I'm trying to divide this array into two new arrays based on the odd or even position of elements. Can anyone provide a solution? New Array 1 (odd positions): [1,2,3,4] New Array 2 (even positions) ...

Exploring the World of GUIs with Python's Tk

I am in search of a helpful resource to guide me on how to connect TKinter with JSON. I would like to input a word, search for that word in the JSON file, and then display the result of the search. Currently, I have my python application running smoothly ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...

The process of assigning a function to an object in JavaScript is currently not functioning properly

After updating a Vue2 project to Vue3, I ran into an issue with Javascript. It seems that the language now prevents me from assigning a function to an object. In the code below, I define a function "bar" within a loop. While I can successfully call the fu ...

AngularJS HTTP request not functioning properly with duplicate requests in Postman

My postman request is working fine, but the equivalent in angularJS isn't. I'm able to get the response I need in Postman, but for some reason, it's not working in Angular. var settings = { "async": true, "crossDomain": true, ...

Discovering elements within an array JSON using Angular JS: A complete guide

The API call response is in JSON format: [ { "RESULT": { "TYPES": [ "bigint", "varchar", "varchar", "varchar", "varchar", "varchar", "date", "varch ...