I want to see if there is a way to see if a value is present in an array of objects.
This is my attempt, but it keeps printing false, what would be the most efficient way to approach this problem?
my attempt
var dog_database = [
{"dog_name": "Joey", "chip_id": "001", "breed": "mixed"},
{"dog_name": "Max", "chip_id": "002", "breed": "beagle"},
{"dog_name": "Izzy", "chip_id": "003", "breed": "mixed"},
{"dog_name": "Frankie", "chip_id": "004", "breed": "terrier"},
{"dog_name": "Star", "chip_id": "005", "breed": "husky"},
{"dog_name": "Goku", "chip_id": "006", "breed": "lab"}
];
wanted_value = "mixed";
var isPresent = Object.keys(dog_database).some(function(k) {
Object.keys(dog_database[k]).some(function(i) {
if (dog_database[k][i] == wanted_value) {
return true;
} else {
return false;
}
});
});
console.log(isPresent);
This want you want?
Use Array.prototype.some for checking if a value exists.
var dog_database = [{
"dog_name": "Joey", "chip_id": "001", "breed": "mixed"
},
{
"dog_name": "Max", "chip_id": "002", "breed": "beagle"
},
{
"dog_name": "Izzy", "chip_id": "003", "breed": "mixed"
},
{
"dog_name": "Frankie", "chip_id": "004", "breed": "terrier"
},
{
"dog_name": "Star", "chip_id": "005", "breed": "husky"
},
{
"dog_name": "Goku", "chip_id": "006", "breed": "lab"
}
];
wanted_value = "mixed";
var isPresent = dog_database.some(dog => dog.breed === wanted_value)
console.log(isPresent);