我有一个对象数组:
const breeds=[{name: 'Golden', temperament: ['friendly', 'kind', 'smart']},{name: 'Husky', temperament: ['alert', 'loyal', 'gentle']},{name: 'Yorkshire Terrier', temperament: ['bold', 'independent', 'kind']}]
我想按选定的“气质”对它们进行排序。假设用户同时选择了“种类”和“友好”,则应该只返回“金色”。
我正在使用javascript和下划线,这是到目前为止我尝试过的:
//selected is an array of selected temperaments
//breeds is the array of objects
function filterTemperaments(selected, breeds) {
return _.filter(breeds, function (breed) {
if (!breed.temperament) breed.temperament = "";
const breedList = breed.temperament;
return breedList.includes(...selected);
}, selected);
}
这似乎只是返回与所选阵列中第一个性情相匹配的品种。例如,如果选择的是['kind', 'loyal']
并且品种是{name:'Golden', temperament: ['kind', 'smelly']}
,尽管与“忠实”的气质不匹配
是否有任何更好的解决方案?提前致谢!!
答案 0 :(得分:1)
const breeds=[{name: 'Golden', temperament: ['friendly', 'kind', 'smart']},{name: 'Husky', temperament: ['alert', 'loyal', 'gentle']},{name: 'Yorkshire Terrier', temperament: ['bold', 'independent', 'kind']}],
selected = ['kind', 'friendly']
const filtered = breeds.filter(b => selected.every(s => b.temperament.includes(s)))
console.log(filtered)
答案 1 :(得分:0)
很容易使用filter
和every
来确定是否有匹配项并返回匹配的值。
const breeds = [{
name: 'Golden',
temperament: ['friendly', 'kind', 'smart']
}, {
name: 'Husky',
temperament: ['alert', 'loyal', 'gentle']
}, {
name: 'Yorkshire Terrier',
temperament: ['bold', 'independent', 'kind']
}]
//selected is an array of selected temperaments
//breeds is the array of objects
function filterTemperaments(selected, breeds) {
return breeds.filter(({ temperament }) => { //here I'm desctructuring the object only to get the temperaments.
return selected.every(selection => temperament.indexOf(selection) !== -1)
})
}
const result = filterTemperaments(['kind', 'friendly'], breeds);
console.log(result)