I have the following JSON object with me:
{
"nodeId": 2965,
"appId": 208,
"navigationType": 0,
"displaySeq": 0,
"displayText": "Delete Testing",
"customerAttribute": "",
"saveAsDefault": false,
"ussdDisplayText": "Delete Testing",
"headerForChild": "",
"Nodes": [
{
"nodeId": 3081,
"appId": 208,
"navigationType": 0,
"displaySeq": 1,
"displayText": "New node2967",
"customerAttribute": "",
"saveAsDefault": false,
"ussdDisplayText": "New node2967",
"headerForChild": "",
"parentNodeId": 2965,
"Nodes": [
{
"nodeId": 3086,
"appId": 208,
"navigationType": 0,
"displaySeq": 1,
"displayText": "abcd",
"customerAttribute": "",
"saveAsDefault": false,
"ussdDisplayText": "New node1",
"headerForChild": "",
"parentNodeId": 3081,
"Nodes": [],
"concatWithHeader": false,
"nodeCode": "208_3085_1",
"parentCode": "3080",
"extResponseType": 0,
"canAdd": false,
"canEdit": false,
"canDelete": false,
"canView": false,
"setChileNode": false
}
],
"concatWithHeader": false,
"nodeCode": "3080",
"parentCode": "RN",
"extResponseType": 0,
"canAdd": false,
"canEdit": false,
"canDelete": false,
"canView": false,
"setChileNode": false
}
],
"concatWithHeader": false,
"nodeCode": "RN",
"parentCode": "ROOT_NODE",
"responseType": 1,
"responseText": "Thank you!",
"dynamicResponseFlag": false,
"extResponseType": 0,
"canAdd": false,
"canEdit": false,
"canDelete": false,
"canView": false,
"setChileNode": false
}
I want the max value of the property **nodeId**
from this object ie 3080
How do I do it? I dont want to sort it. Just get the max value.
I tried this:
var data = rootNode;
var maxProp = "nodeId";
var maxValue = -1;
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var value = data[prop];
if (value > maxValue) {
maxProp = prop;
maxValue = value;
}
}
}
But this iterates over the properties, not on the children. Hence I get only the first value as the max one.
Try this:
var nodes = data.Nodes, // data is your json
maxProp = "nodeId",
maxVal = 0, maxInd = 0;
for (var i = 0; i < nodes.length; i++) {
var value = parseInt(nodes[i][maxProp], 10);
if (value > maxVal) {
maxVal = value;
maxInd = i;
}
}
console.log(nodes[maxInd]) // array with maximal nodeId
You could also use Math.max
if you have an array of the values from which the max should be determined. Using ES5's array map
, you can pull this from your nodes. If you can't support ES5 (IE9+), you could also use the jQuery or Underscore.js implementations.
var maxProp = 'nodeId',
propValues, maxvalue;
propValues = data.Nodes.map(function(node) {
return node[maxProp];
});
maxValue = Math.max.apply(null, propValues);
JSFiddle: http://jsfiddle.net/g2YeW/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.