Comparing values from an object and an array to get output from the array
Solution 1:
Not sure there is a "best" way because it very much depends on the shape of your data. But what you have isn't far off.
It seems like a small helper function might make this more extensible. Something like
var current_data = ['true', 'visiting-today', 'DVM-Wiessman','J-001'];
const VET_INDEX = 2
const RESULT_INDEX = 3
var dog_database = [
{"dog_name": "Joey", "chip_id": "001", "breed": "mixed", "vets":['DVM-Wiessman','DVM-White']},
{"dog_name": "Max", "chip_id": "002", "breed": "beagle", "vets":'DVM-Wiel'},
{"dog_name": "Izzy", "chip_id": "003", "breed": "mixed", "vets":'DVM-James'},
{"dog_name": "Frankie", "chip_id": "004", "breed": "terrier","vets":'DVM-Smith'},
{"dog_name": "Star", "chip_id": "005", "breed": "husky", "vets":['DVM-Johns','DVM-Pearson']},
{"dog_name": "Goku", "chip_id": "006", "breed": "lab", "vets":'undecided'},
];
function findByVet(vetName) {
return dog_database.find((row) => row.vets == vetName || row.vets.includes(vetName))
}
if (findByVet(current_data[VET_INDEX])) {
console.log( current_data[RESULT_INDEX] )
} else {
console.log( "does not exist" )
}
As you can see I added a couple constants to explain/show what each field in current_data
is supposed to represent. Not sure that RESULT_INDEX
is really the right name but I'm sure you could make that more informative/better named.
Not sure how much control you have over the current_data
, but if that were an object, more like
var current_data = {
"something": true,
"status": "visiting-today"
"vet": "DVM-Wiessman",
"result": "J-001"
}
(I'm sure the keys here are not correct... just guessing at what they might be called)
Then the code would be a little easier to read and understand because it'd look something like
if (findByVet(currentData.vet)) {
return currentData.result;
} else {
return "does not exist"
}
or something along those lines.