如果使用Dataweave存在元素,则向数组添加键

如果使用Dataweave存在元素,则向数组添加键,dataweave,mulesoft,Dataweave,Mulesoft,我有一个JSON对象,它的字段有subject1、subject2、subject3,值为字符串数组 如果任何搜索元素存在于分配给字段subject1、subject2、subject3的字符串数组中,那么我需要将键或该字段从Json对象添加到现有数组(myArray)中 %dw 2.0 var myArray=[]; 变量科目={ “主题1”=[“A部分”、“B部分”、“C部分”], “主题2”=[“B节”、“D节”、“E节”], “主体3”=[“C节”、“F节”、“G节”], } fun g

我有一个JSON对象,它的字段有subject1、subject2、subject3,值为字符串数组

如果任何搜索元素存在于分配给字段subject1、subject2、subject3的字符串数组中,那么我需要将键或该字段从Json对象添加到现有数组(myArray)中

%dw 2.0
var myArray=[];
变量科目={
“主题1”=[“A部分”、“B部分”、“C部分”],
“主题2”=[“B节”、“D节”、“E节”],
“主体3”=[“C节”、“F节”、“G节”],
}
fun getSubjects(部分)=映射mapObject(值、键、索引)->
如果(value contains key)myArray我想这就是您试图做的;因为数据在dataweave中是不可变的,如果您想在更改数组内容的同时迭代集合,就必须使用reduce之类的东西

%dw 2.0

var subjects = {
    "subject1": ["sectionA", "sectionB", "sectionC"],
    "subject2": ["sectionB", "sectionD", "sectionE"],
    "subject3": ["sectionC", "sectionF", "sectionG"]
}

var section = "sectionA"

fun getSubjects(section) = subjects pluck $$ reduce ((subject, myArray=[]) ->
    if (subjects[subject] contains section) myArray << subject
    else myArray
)

---
{
    subjects: getSubjects(section)
}
我认为这就是您试图做的;因为数据在dataweave中是不可变的,所以如果您想在更改数组内容的同时迭代集合,就必须使用诸如reduce之类的工具

%dw 2.0

var subjects = {
    "subject1": ["sectionA", "sectionB", "sectionC"],
    "subject2": ["sectionB", "sectionD", "sectionE"],
    "subject3": ["sectionC", "sectionF", "sectionG"]
}

var section = "sectionA"

fun getSubjects(section) = subjects pluck $$ reduce ((subject, myArray=[]) ->
    if (subjects[subject] contains section) myArray << subject
    else myArray
)

---
{
    subjects: getSubjects(section)
}

还有一种方法可以做到这一点,如下所示,我们将发送需要匹配的变量和字符串

%dw 2.0
var myArray = []
var subjects = {
"subject1" : ["sectionA", "sectionB", "sectionC"],
"subject2" : ["sectionA", "sectionD", "sectionE"],
"subject3" : ["sectionC", "sectionF", "sectionG"],
 }
 
fun adding(inputarray,matchingkey)= flatten(inputarray mapObject ((value, key) -> 
 (("myArray"): (myArray ++ [key])) if ((value) contains matchingkey) 
 ) pluck $)
 
---
 
adding(subjects,"sectionC")
输出为:

[
  "subject1", 
  "subject3"
]


还有一种方法可以做到这一点,如下所示,我们将发送需要匹配的变量和字符串

%dw 2.0
var myArray = []
var subjects = {
"subject1" : ["sectionA", "sectionB", "sectionC"],
"subject2" : ["sectionA", "sectionD", "sectionE"],
"subject3" : ["sectionC", "sectionF", "sectionG"],
 }
 
fun adding(inputarray,matchingkey)= flatten(inputarray mapObject ((value, key) -> 
 (("myArray"): (myArray ++ [key])) if ((value) contains matchingkey) 
 ) pluck $)
 
---
 
adding(subjects,"sectionC")
输出为:

[
  "subject1", 
  "subject3"
]


嘿@chakez!你能提供var.section的内容吗?另外,如果你能添加一个输入示例和预期的输出?谢谢。你想要什么o/p,在这里详细解释一下你需要什么类型的o/p?@chakez你不能这样做,因为所有的数据类型在dataweave中都是不可变的。你必须递归地这样做,essenti每次都用更新的内容创建一个新数组。嘿@chakez!你能提供var.section的内容吗?另外,如果你能添加一个输入示例和预期的输出?谢谢。你想要什么o/p,请在这里详细解释一下,比如你需要什么类型的o/p?@chakez你不能这样做,因为所有的数据类型都是不可变的可以在dataweave中使用。您必须递归地执行此操作,本质上每次使用更新的内容创建一个新数组。