'$indexOfArray match array element field with value
I have a dataset that looks like this
{
...
array:[
{
field1: 'value1'
},
{
field1: 'value2',
field2: 'value3'
}
]
...
}
I receive 2 strings and depending on some parameters I decide if those strings are a field1 type or a field2 type. What I need to do is find the index of those strings in my array objects. For example for the string 'value1' I should get 0 and for the strings 'value2' and 'value3' I should get 1.
If I create my query dynamically and for example I search with $indexOfArray for "$array.field2" the first occurence will have the index 0, even though it's the second element in array, because it's the first one that has the field2 field. How can I iterate through all of my array and find the index of my string?
Solution 1:[1]
I finally found one way to do it thanks to this answer indexOfArray with map
The idea is to map the array so that it contains boolean values and find the true one.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul |
