我具有以下数组结构:
[{…}, {…}, {…}, {…}, {…}, {…}]
此数组中的一个对象可能看起来像这样:
[
{
name: 'testing',
other: 'value',
ratings: [{category : 'passives'} , {category : 'detractor'}]
},
{
name: 'testing2',
other: 'value',
ratings: [{category : 'detractor'}]
}
]
我想选择数组中包含评级为被动类别的所有对象。
因此,使用上述对象,返回值应类似于:
[
{
name: 'testing',
other: 'value',
ratings: [{category : 'passives'} , {category : 'detractor'}]
}
]
原因是因为这是数组中唯一具有包括被动类别在内的等级的对象。
我尝试过类似的事情:
const response = 'passives'
const ape = object.filter(project => {
return project.ratings.filter(item => {
return item.category === response
})
})
答案 0 :(得分:3)
即使内部.filter()
返回一个空数组,外部.filter()
也会将其评估为“真”,因此它实际上不会过滤任何内容。
如果您需要返回布尔值(true
或false
),则根据嵌套数组是否包含具有所需属性值的对象为基础,Array.prototype.some()
是一个完美的选择
const src = [{name:'testing',other:'value',ratings:[{category:'passives'},{category:'detractor'}]},{name:'testing2',other:'value',ratings:[{category:'detractor'}]}],
result = src.filter(({ratings}) =>
ratings.some(({category}) =>
category == 'passives'))
console.log(result)
.as-console-wrapper{min-height:100%;}
答案 1 :(得分:0)
您可以尝试
const arr = [
{
name: "testing",
other: "value",
ratings: [{ category: "passives" }, { category: "detractor" }],
},
{
name: "testing2",
other: "value",
ratings: [{ category: "detractor" }],
},
]
const res = arr.filter((obj) =>
obj.ratings.find((rating) => rating.category === "passives") !== undefined
)
console.log(res)
答案 2 :(得分:0)
这是工作示例:
let arr = [
{
name : 'testing',
other: 'value',
ratings : [{category : 'passives'} , {category : 'detractor'}]
},
{
name : 'testing2',
other: 'value',
ratings : [{category : 'detractor'}]
}
];
const response = 'passives'
const ape = [];
arr.map(project => {
const filtered = project.ratings.filter(item => item.category === response);
if(filtered.length > 0) {
ape.push(project);
}
});
console.log(ape);