arraysjsondistinctdistinct-valuesjsonata

devide values with JSONata


JSONata is honestly driving me crazy. I asked something similar a couple of weeks ago, but I still don't know what I'm doing so here I am again.

What I'm working with:

[[  {
    "time": "2024-04-26",
    "value": 40
  },
  {
    "time": "2024-04-27",
    "value": 10
  },
  {
    "time": "2024-04-28",
    "value": 20
  }
],
[  {
    "time": "2024-04-26",
    "value_2": 5
  },
  {
    "time": "2024-04-27",
    "value_2": 2
  },
  {
    "time": "2024-04-28",
    "value_2": 4
  }
]]

What I want is to get the distinct values for time and devide the values - value/value_2:

[  {
    "time": "2024-04-26",
    "value": 8
  },
  {
    "time": "2024-04-27",
    "value": 5
  },
  {
    "time": "2024-04-28",
    "value": 5
  }
]

I tried something like this but I only get the distinct values for time.

$type($) = 'array' ? 
(($count($) ) > 0 ? 
$map($[0], function($v, $i, $a) 
{ { "time": $v.time, 
"value": $v.value/ $v.value_2 } })[]: []): undefined 

Output:

[
  {
    "time": "2024-04-26"
  },
  {
    "time": "2024-04-27"
  },
  {
    "time": "2024-04-28"
  }
]

Solution

  • How about this:

    (
      /* convert the array to an map of date to value */
      $first := $[0].{time: value};
      $second := $[1].{time: value_2};
    
      /* iterate over the keys, lookup the values
      $keys($first).{
          "time": $,
          "value": $lookup($first, $) / $lookup($second, $)
      }
    )