Forum Discussion

kmiesse's avatar
kmiesse
Contributor
8 years ago

Add index of element in array to the element

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
}
]
}

3 Replies

  • tstack's avatar
    tstack
    Former Employee

    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}))
    • kmiesse's avatar
      kmiesse
      Contributor

      WOW! Thank you so much! It works wonderfully.