DataWeave 将消息转换为两个带数字的数组

DataWeave transform message two arrays with numbers

我想用数字比较两个数组(如 input2)。如果价格有所不同,大约增加 5%,那么我想发送电子邮件。我这样试过,但它只给出了与相同数字匹配的数字。但我只想要这个价格,它增加了 5%。

%dw 2.0
output application/json 

var input2 = [{
            "T": "GIK",
            "c": 10.02
       
        },
        {
            "T": "EXTR",
            "c": 4.43
          
        },
        {
            "T": "TANH",
            "c": 2.34
          
        },
        {
            "T": "VSAT",
            "c": 34.24
          
        },
        {
            "T": "KIMpL",
            "c": 25.9102
            
        }]
---
payload.results.c reduce (item, acc = []) -> if (input2.c contains item) acc + item else acc

从您的脚本中可以看出,您希望数字(input2 元素的属性 c)偏离负载中相同属性 c 的百分比。如果你只需要比较每个数字与另一个数组中每个数字的百分比,这个脚本就可以做到。我用一个函数来计算百分比差异。

%dw 2.0
output application/json 
import * from dw::core::Arrays
var maxPercentageDifference=5
fun percentageDifference(a,b)=abs(a-b)/((a+b)/2)*100
var input2 = [
    {
        "T": "GIK",
        "c": 10.02
    
    },
    {
        "T": "EXTR",
        "c": 4.43
    },
    {
        "T": "TANH",
        "c": 2.34       
    },
    {
        "T": "VSAT",
        "c": 34.24
    },
    {
        "T": "KIMpL",
        "c": 25.9102
    }
]
---
payload.results.c 
    reduce (item, acc = []) -> if (input2.c some (percentageDifference(item, $) <= maxPercentageDifference)) acc + item else acc

输入:

{
    "results": [
        {
            "T": "GIK",
            "c": 10.05

        },
        {
            "T": "EXTR",
            "c": 4.41
        
        },
        {
            "T": "TANH",
            "c": 8
        
        },
        {
            "T": "VSAT",
            "c": 44
        
        },
        {
            "T": "KIMpL",
            "c": 25.9102
            
        }
    ]
}

输出:

[
  10.05,
  4.41,
  25.9102
]

然而,如果你想在比较值之前匹配属性“T”中的 ID,只需将上面的脚本正文更改为:

payload.results 
    filter ((item, index) ->  percentageDifference((input2 firstWith($.T == item.T)).c, item.c) <= maxPercentageDifference )

新输出:

[
  {
    "T": "GIK",
    "c": 10.05
  },
  {
    "T": "EXTR",
    "c": 4.41
  },
  {
    "T": "KIMpL",
    "c": 25.9102
  }
]