Retrieve the maximum value from a JSON object using JavaScript

This question seems straightforward, but I'm struggling to solve it.

Could someone help me with a JavaScript solution to retrieve the largest value from this JSON object?

{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}

I am specifically looking for:

"two":35 

as it contains the highest value.

Any assistance would be greatly appreciated.

Answer №1

let jsonData = '{"info":{"first":18,"second":27,"third":37,"fourth":5,"fifth":12},"information":{"name":"Satisfied with the assistance"}}'
let infoData = JSON.parse(jsonData).info
let maxProperty = null
let maximumValue = -1
for (let property in infoData) {
  if (infoData.hasOwnProperty(property)) {
    let val = infoData[property]
    if (val > maximumValue) {
      maxProperty = property
      maximumValue = val
    }
  }
}

Answer №2

If you happen to be using underscore library:

var max_key = _.invert(data)[_.max(data)];

Here's a breakdown of how this code snippet functions:

var data = {apple:15, banana:30, cherry:20, date:5, fig:12};
var inverted = _.invert(data); // {15:'apple', 30:'banana', 20:'cherry', 5:'date', 12:'fig'};
var max = _.max(data); // 30
var max_key = inverted[max]; // {15:'apple', 30:'banana', 20:'cherry', 5:'date', 12:'fig'}[30] => 'banana'

Answer №3

This is my code snippet to find the largest key in an object

function findLargestKey(obj) {  
  var max, k; // set max initially undefined to handle negative keys  
  for (var key in obj) { if (obj.hasOwnProperty(key)) { max = parseInt(key); break; }} //get any key  
  for (var key in obj) { if (obj.hasOwnProperty(key)) { if((k = parseInt(key)) > max) max = k; }}  
  return max;  
} 

Answer №4

Once you've parsed JSON, another way to work with the data is by iterating through the object.

var jsonData = jQuery.parseJSON('{"apple":9,"banana":3,"cherry":12,"date":7,"fig":15}' );

var highestValue = 0;

for (item in jsonData)
{
     if (jsonData[item] > highestValue)
     {
          highestValue = jsonData[item];   
     }
}

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

Error: Attempting to access a property named '_updatedFibers' on an undefined object is not possible due to a TypeError

I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading '_updatedFibers') at requestUpdateLane (react-dom.development.js:25411:23) at updateContainer (react-dom.development.js:28810:14) at ReactDOMHydra ...

What is the optimal approach for managing script initialization on both desktop and mobile devices?

I have implemented a feature on my website that can detect whether the viewer is using a mobile device. Additionally, I have created a JavaScript script that adjusts settings based on whether the user is on a mobile device or not. However, I am wondering ...

jQuery "ooze navigation" - precise pixel rounding

After successfully programming my jQuery slime menu, I am facing a minor issue. Although the menu works beautifully, I have noticed that when I move the arrow and the ending circle of the slime separately, they do not always connect accurately if the curso ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Searching with nested strings for keys in JavaScript using JSON structures

Given a json object in JavaScript like so: var data = { blog : { title: "my blog", logo: "blah.jpg", }, posts : [ { title: "test post", content: "<p>testing posts</p><br><p&g ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

Tips for executing an artillery script with customizable parameters

execute my-script.yaml with artillery To access the target, a token is required for authentication. How can I execute the script above using a token? For example: execute my-script.yaml using token 983r2fh29hf2893yr72 ...

The div on my webpage is not loading its content as expected when using JavaScript

I am having trouble continuously loading the content of a div from another page. Using alert worked fine, but the page data is not loading. JavaScript <script> $(document).ready(function(){ setInterval(function(){$("#loadAvailable").load("update.p ...

Unlocking elements in Vue.js through functions

Looking to dynamically add a class to the label element when focusing on an input element below it. The current HTML and JS code I'm using is as follows: HTML: <label for="formProductId" ref="productIdLabel" class="form-element-title">Product ...

What causes variables and functions to behave differently when it comes to hoisting?

I've recently been delving into some documentation and have noticed some inconsistencies in hoisting patterns within JavaScript. Consider the following examples: When it comes to functions, function abc(){ console.log("worked") } abc(); OUTPUT : ...

Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js? I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend. Here is my vue application: ...

Disabling Camera Dampening in a 3D Environment Upon Click

I am currently working on a project that involves implementing a damping effect for the camera when the user stops rotating it using their mouse. While this effect is important, I also want to provide users with the option to disable the damping effect by ...

Instructions on creating a customized format for a JSON file that stores pairs within a Python list

I currently have a list called name_class that contains pairs of names and labels like ['2_255.png', 255], ['1_256.png', 256], ['2_257.png', 257]. My goal is to generate a JSON file with a specific structure: { "names": [ ...

Obtain image file paths dynamically in a folder using Nuxt

https://i.sstatic.net/3FKZH.png Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing im ...

Is it possible for a nonce to be utilized for multiple scripts, or is it restricted to

Exploring the Origins About a year ago, our company embarked on a journey to implement CSP throughout all our digital platforms. Each of these platforms was built using an express.js + react framework. In order to adhere to the guideline that "Each HTTP r ...

Browser refusing to acknowledge jQuery/JavaScript (bootstrap)

Here is where I include the necessary jQuery libraries and my custom jQuery code: <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script src= ...

What are some effective methods for troubleshooting npm modules?

Typically, the process involves installing React with yarn/npm install react and then using it by importing React from 'react' Imagine you need to debug a React source code, so you clone a GitHub repository. But how do you incorporate this sour ...

Is it possible to transform a JSON object into a JAXB object?

I have been dealing with JAXB objects and now I need to switch to using JSON instead of XML. Can anyone provide guidance on how to go about this? I don't want to completely replace the codebase with JSON objects. Is there a way to convert JSON to JAX ...

Struggling to get the Ant design button to launch an external link in a new tab using React and NextJS

I have an Ant button set up like this: <Button style={{ borderRadius: '0.5rem' }} type="default" target="_blank" ...