06-30-2021 05:22 AM
Hello,
I have this json:
{
"a": "Hello Word",
"b": 1,
"c": "some",
"d": 10,
"nested": [{
"m": "hey",
"o": 10,
"p": "hello",
"q": 100
}]
}
I am trying to multiply each number field by 10 and the output structure needs to be the same.
So far I’ve managed to get it worked for an Object using: $.mapValues((value, key) => !isNaN(value) ? value * 10 : value)
but I don’t really know how can I do that for Arrays.
Any tips?
Thank you!
06-30-2021 05:27 AM
Without giving you the answer outright 😉, did you look at the Array.map() function?
https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1438091/Array+Functions+and+Properties#Arr...
Also see the very bottom of this page for a similar example:
https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1438042/Understanding+Expressions+in+SnapL...
06-30-2021 05:37 AM
Yes but .map() function transforms every element from the Array, I only need to change the fields where there are numbers. Is there a way that I can use conditional logic inside of the .map() function?( if typeof value == ‘number’ then value * 10 else value
06-30-2021 06:01 AM
Absolutely - the expression in the map function can use ternary logic just like you have in your example updating the object elements.
Assuming an input array:
{ "myArray": [ "abc", 13, "def", 15 ] }
This works as I believe you are requesting:
$myArray.map(x => x instanceof Number ? x * 10 : x)
{ "updatedArray": [ "abc", 130, "def", 150 ] }
06-30-2021 06:24 AM
You are right, in this case it works but in my case I have an array of objects which I finally managed to work with this: jsonPath($, "$nested[*]").map(x => x.mapValues((value, key) => !isNaN(value) ? value * 10 : value))
Input:
"nested": [{"m": "hey", "o": 10, "p": "hello", "q": 100}]
Output:
"nested": [{"m": "hey", "o": 100, "p": "hello", "q": 1000}]
Thank you @koryknick for your guidance!