08-07-2017 06:47 AM
How do I add the index of the element in an array to the element? I have the following doc that I simply want to add the index of the element in the array1 array to each element in the array1 array:
{
“field1”: “46”,
“array1”: [
{
“number”: 1,
“code”: “TSD”
},
{
“number”: 11,
“code”: “NONE”
}
]
}
Desired result:
{
“field1”: “46”,
“array1”: [
{
“number”: 1,
“code”: “TSD”,
“index”: 0
},
{
“number”: 11,
“code”: “NONE”,
“index”: 1
}
]
}
08-07-2017 08:37 AM
Look at this solution.
You can split the array and add snap.in.totalCount-1 as an index.
After splitting you need to reform the array and add the fields back together.
snap.in.totalCount-1 ==> $index in the mapper after JSON split
array index_2017_08_07.slp (8.8 KB)
08-07-2017 09:23 AM
The expression language is a functional subset of JavaScript, so often times you can search for the JavaScript solution to a problem and make some small changes to make it work.
In this case, you’ll want to use the ‘map()’ method on arrays to transform each element:
The ‘map()’ method takes an arrow function that will be passed the element in the array and the index of that element. So, we can extend() the existing element to add in the index that is passed into the callback function.
The result looks like this:
$.array1.map((elem, elemIndex) => elem.extend({index: elemIndex}))
08-07-2017 11:00 AM
WOW! Thank you so much! It works wonderfully.