Searching for an element in a JavaScript array using the find method
const array = [{
"key1": "val1",
"key2": "val2",
"key3": "val3",
"key4": "val4",
"key5": "val5",
},
{
"key1": "val6",
"key2": "val7",
"key3": "val8",
"key4": "val9",
"key5": "val10"
}]
We are looking to search for the value searchvalue
. It is expected to match with val1
, and if it does, we want to retrieve key5
:
array.find((element) => element.key1 === searchvalue).key5)
If no matching element.key1 === searchvalue
is found, then the search should be based on key2
and key6 of the result:
array.find((element) => element.key2 === searchvalue).key5)
At present, the workflow involves:
var arrayElement = array.find((element) => element.key1 ===
searchvalue)
const value = (arrayElement !== undefined ) ? arrayElement.key5: array.find((element) => element.key2 ===
searchvalue).key6;