我想通过对象中的特定值过滤对象数组。
在我提供的示例中,我想通过数组 'characteristics' 中的值过滤数组 'pets'。例如,在我使用参数 'loyal' 调用函数的地方,我只希望返回 dog 值的对象,因为只有 dog 具有该特征。
在我调用该函数的那一刻,即使只有 dog 的对象在其特性数组中具有该值,也会返回两个对象。
const pets = [
{
name: 'dog',
characteristics: [
{
value: 'loyal'
},
{
value: 'big'
}
]
},
{
name: 'cat',
characteristics: [
{
value: 'fluffy'
},
{
value: 'small'
}
]
},
]
function filterPets(pets, characteristic) {
return pets.filter(function(pet) {
return pet.characteristics.filter(o => o.value.includes(characteristic));
})
}
console.log(filterPets(pets, 'loyal'));
那是因为对于characteristics
您正在使用的检查filter
,它总是返回一个数组(即使是一个空白数组),即使是一个空白数组也是一个真值,因此外部filter
保留您检查的每个宠物。对于该内部检查,您想要some
,而不是filter
,因此您会获得一个标志,用于判断是否有任何条目匹配:
function filterPets(pets, characteristic) {
return pets.filter(function(pet) {
return pet.characteristics.some(o => o.value.includes(characteristic));
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^
});
}
const pets = [
{
name: 'dog',
characteristics: [
{
value: 'loyal'
},
{
value: 'big'
}
]
},
{
name: 'cat',
characteristics: [
{
value: 'fluffy'
},
{
value: 'small'
}
]
},
];
function filterPets(pets, characteristic) {
return pets.filter(function(pet) {
return pet.characteristics.some(o => o.value.includes(characteristic));
});
}
console.log(filterPets(pets, 'loyal'));
只是它的价值,我认为特性是唯一的(你不能有“忠诚”两次),所以你可能更愿意让那些在Set
这样你就可以比更方便地查询到.some(o => o.includes(characteristic))
。例如:
const pets = [
{
name: "dog",
characteristics: new Set(["loyal", "big"]),
},
{
name: "cat",
characteristics: new Set(["fluffy", "small"]),
},
];
function filterPets(pets, characteristic) {
return pets.filter(function(pet) {
return pet.characteristics.has(characteristic);
});
}
现场示例:
const pets = [
{
name: "dog",
characteristics: new Set(["loyal", "big"]),
},
{
name: "cat",
characteristics: new Set(["fluffy", "small"]),
},
];
function filterPets(pets, characteristic) {
return pets.filter(function(pet) {
return pet.characteristics.has(characteristic);
});
}
console.log(filterPets(pets, "loyal"));
console.log("Don't worry about the {} for characteristics, the Stack Snippets console doesn't know how to display Set objects. Look in the real console if you want to double-check the set.");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句