user2203384 user2203384 - 1 month ago 7
jQuery Question

Get object row by value

I have an object:

{
"status": 200,
"error": false,
"msg": "Successful response",
"data": {
"horodate": [ "2016-10-13 00:00:00", "2016-10-13 00:30:00", ... ],
"value": [ 2609.479, 2390.026, 2320.394, 2276.602, 2247.151, ... ]
}
}


I'm getting the max and min value:

$.getJSON(url, function (data) {
// ...
var arr = Object.keys(data['data']['value']).map(function(key) {
return data['data']['value'][key];
});
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
console.log(min); //2609.479
console.log(max); //2247.151


But how can I get the
horodate
of those min and max values when I retrieve min and max from the object?

Answer

You can get the min index and then get the horodate corresponding to this index:

data = {
  "status": 200,
  "error": false,
  "msg": "Successful response",
  "data": {
    "horodate": [ "2016-10-13 00:00:00", "2016-10-13 00:30:00", "2016-10-13 01:00:00", "2016-10-13 01:30:00", "2016-10-13 02:00:00"], 
    "value": [ 2609.479, 2390.026, 2320.394, 2276.602, 2247.151]
  }
}
var values_arr = data['data']['value']  
var horodates_arr = data['data']['horodate']  

var date_for_value = function(value){
  var min_index = values_arr.indexOf(value);
  return horodates_arr[min_index];  
}

var min = {'value': Math.min.apply(null, values_arr),
           'horodate': date_for_value(min['value'])}

var max = {'value': Math.max.apply(null, values_arr),
           'horodate': date_for_value(max['value'])}

console.log(min); //Object { value=2247.151,  horodate="2016-10-13 02:00:00"}
console.log(max); //Object { value=2609.479,  horodate="2016-10-13 00:00:00"}