03-16-2023 05:38 PM
I’m trying to understand the documentation for the Array function toObject.
It uses [‘zero’, ‘one’, ‘two’].toObject((x, index) => index, x => x.contains(‘two’)) as an example, which returns {“0”: false, “1”: false, “2”: true}.
What does the (x, index) portion of the expression mean? If I reverse the order to {index, x}, use {index}, or use index then the output always returns {zero:false, one:false, two:true}. What is (x, index) and why is it special here?
03-17-2023 01:36 AM
Hello @tarena,
The x refers to the element in the array, and the index refers to the element’s index in the array.
You can name these parameters differently.
e.g.
x = 'zero'
index = 0
x = 'one'
index = 1
x = 'two'
index = 2
The first callback function sets the keys of the object:
(x, index) => index
By this callback function, the keys are set to the corresponding index of the element in the array.
{
"0":
"1":
"2":
}
The second callback function (optional) sets the values of the object:
x => x.contains('two')
By the above callback function, the elements from the array are evaluated using contains(‘two’) String function and the value is set accordingly.
{
"0":false
"1":false
"2":true
}
Let me know if this makes things more understandable.
BR,
Aleksandar.
03-17-2023 08:47 AM
Thank you for your answer. I think I can narrow my question. ‘x’ and ‘index’ are not features of my object. They’re keywords for the expression interpretation. Are there other keywords? Why does the index expression need two parameters (x, index) and for them to be in that order?