Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

anypoint studio - How to check if any values in an array is not null in Dataweave 2.0?

I am mapping my payload to a new payload and adding an Errors array in where the output looks like this. :

payload : [{

"test: "test",

 "test2" : "",

 "test3" : "test3"

},
{

"test: "test",

 "test2" : "test2",

 "test3" : "test3"

}]

Expected output : ` payload : [{

"test: "test",

 "test2" : "",

 "test3" : "test3",

 "Errors" : {

  "test2" : "Test2 is NULL"

  }

},
{

"test: "test",

 "test2" : "test2",

 "test3" : "test3",

 "Errors" : {

  }

}]`

Expected Output : I want to get an output where I only get all objects from Payload where Errors array has any key with not null values otherwise it should be filtered out.

I am using below expression to achieve but this is not feasible as it requires me to add a null check for each key in Errors array.

errArr."Errors" filter ((item, index) -> item."test" != "" or item."test2" != "" or

item."test3" != "")

There has to be a better way to do this? Is there a way to just check values of every item (key)without defining their name?

question from:https://stackoverflow.com/questions/65878126/how-to-check-if-any-values-in-an-array-is-not-null-in-dataweave-2-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this, explanations follow the code:

%dw 2.0
output application/json

var data = [{
    "test": "test",
     "test2" : "",
     "test3" : "test3"
    },
    {
    "test": "test",
     "test2" : "test2",
     "test3" : "test3"
    
    }
]

---
data map {
    ($),
    errors: $ mapObject (v,k) -> (
        if (isEmpty(v)) {(k): "$(k) is empty"} else {}
    )
}

Here's the algorithm along with links in the documentation:

  1. Iterate over the objects in the array using map
  2. Create a new object and add the existing (key,value) pairs in the new object using the dynamic elements feature.
  3. Add the errors field to the new object. Calculate the errors object using the mapObject function that identifies all empty (notice I say empty and not just null) fields.

My advice to you is to ensure you provide an appropriately scoped input and output set of sample data when you ask questions. This will ensure that you will get your answers to your questions in a more timely basis.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...