如何查看某个值是否存在于对象数组中?
How can I see if a value is present in an array of objects?
我想看看是否有办法查看对象数组中是否存在某个值。
这是我的尝试,但它一直打印错误,解决这个问题的最有效方法是什么?
我的尝试
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);
这个要你要吗?
使用 Array.prototype.some
检查值是否存在。
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);
我想看看是否有办法查看对象数组中是否存在某个值。
这是我的尝试,但它一直打印错误,解决这个问题的最有效方法是什么?
我的尝试
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);
这个要你要吗?
使用 Array.prototype.some
检查值是否存在。
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);