Determine top value from a JSON array

Matt Lightbourn :

I'm trying to create a chart which uses an input set of data which I then turn into percentages so that the chart is always between the range of -100 and 100.

From the array of JSON data I want to work out the max number (positive value, generally) and min number (likely to be a negative but turned into a positive using a - before the variable).

I then want to work out which of those two 'positive' values is higher and mark that as the top value.

I then for each value from the data, want to divide the (timeline_value by the top_value) multiplied by 100 and rounded.

For each of those values, I need to add them to individual arrays. One of them is to calculate the rectangle width chartWidth, one to work out the rect start position chartStart (for positive values its 152, for negative values, it is 148 minus chartWidth).

For chartColor, I want to have it predefined that revenue is always green (#28CE6D), expenses is always red (#DF3456) and profit is always blue (#4DC7EC). Below is the data set that is driving my chart that I need to create from the input data:

var chartStart = [152, 84, 152]
var chartWidth = [100, 64, 36]
var chartNames = ["$7,110 Revenue", "$4,539 Expenses", "$2,571 Profit"]
var chartColor = ["#28CE6D", "#DF3456", "#4DC7EC"]

Here's the bit I'm stuck on where I'm trying to create the above set from. Thanks

var input_data = {
  timeline_balances: [
    {
      timeline_name: "Revenue",
      timeline_value: 7110,
      currency: "$"
    },
    {
      timeline_name: "Expenses",
      timeline_value: -4539,
      currency: "$"
    },
    {
      timeline_name: "Profit",
      timeline_value: 2571,
      currency: "$"
    }
  ]
}

var max_value = input_data.timeline_balances.timeline_value.max_value
var min_value = -input_data.timeline_balances.timeline_value.min_value

if (max_value > min_value) {
  top_value = max_value;
} else {
  top_value = min_value;
}
ellipsis :

You have to use a loop to get values from the object as the object is inside an array

var input_data = {
  timeline_balances: [{
      timeline_name: "Revenue",
      timeline_value: 7110,
      currency: "$"
    },
    {
      timeline_name: "Expenses",
      timeline_value: -4539,
      currency: "$"
    },
    {
      timeline_name: "Profit",
      timeline_value: 2571,
      currency: "$"
    }
  ]
}
var top_value=-10;
input_data.timeline_balances.forEach(e=>{
var max_value = e.timeline_value
var min_value = -1*e.timeline_value
if (max_value > min_value) {
if(max_value>top_value)
  top_value = max_value;
} else {
if(min_value>top_value)
  top_value = min_value;
}
})
console.log(top_value)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7219&siteId=1
Recommended