我想根据categories
数组中的条件从otherCategories
数组中过滤项目。
如果otherCategories
包含一个对象,其中title
匹配categories.subCategory[i].title
中的一个标题,而name
匹配categories.subCategory[i].details.name
,则仅过滤该对象,例如, categories
。
var categories = [
{
title:"item1",
subCategory:[
{
title:"subCat1",
details:{
name:"detail1",
email:"test@test.com"
}
},
{
title:"subCat2",
details:{
name:"detail2",
email:"test@test.com"
}
}
]
},
{
title:"item2",
subCategory:[
{
title:"subCat1",
details:{
name:"detail3",
email:"test@test.com"
}
},
{
title:"subCat2",
details:{
name:"detail2",
email:"test@test.com"
}
}
]
}
]
var otherCategories = [
{
title:"subCat1",
name:"detail1"
}
]
预期结果
categories = [
{
title:"item1",
subCategory:[
{
title:"subCat1",
details:{
name:"detail1",
email:"test@test.com"
}
},
{
title:"subCat2",
details:{
name:"detail2",
email:"test@test.com"
}
}
]
}]
答案 0 :(得分:0)
使用Array.reduce,Array.filter和Array.some
otherCategories
数组转换为标题为键,名称为值的对象categories
数组,其中有些subCategory
存在匹配的值
var categories = [{title:"item1",subCategory:[{title:"subCat1",details:{name:"detail1",email:"test@test.com"}},{title:"subCat2",details:{name:"detail2",email:"test@test.com"}}]},{title:"item2",subCategory:[{title:"subCat1",details:{name:"detail3",email:"test@test.com"}},{title:"subCat2",details:{name:"detail2",email:"test@test.com"}}]}];
var otherCategories = [{title:"subCat1",name:"detail1"}];
var obj = otherCategories.reduce((a,c) => Object.assign(a,{[c.title]:c.name}), {});
categories = categories.filter(v => v.subCategory.some(o => obj[o.title] === o.details.name));
console.log(categories);
答案 1 :(得分:0)
另一种通常适用于示例中的简单对象的方法是将@Entity
@Table(name = "eq_panel_category_option")
public class PanelCategoryOption {
@EmbeddedId
private PanelCategoryOptionId id;
}
数组转换为“字符串化”对象的数组,然后通过比较“字符串化”来过滤@Embeddable
public class PanelCategoryOptionId implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "panel_id", referencedColumnName = "panel_id"),
@JoinColumn(name = "category_id", referencedColumnName = "category_id")})
private PanelCategory panelCategory;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "category_option_id", referencedColumnName = "id", insertable = false, updatable = false),
@JoinColumn(name = "category_id", referencedColumnName = "category_id", insertable = false, updatable = false)})
private CategoryOption categoryOption;
}
所需otherCategories
键值对的版本到转换后的categories
数组。
但是,值得注意的是,JavaScript无法保证对象属性顺序(尽管许多浏览器会保留属性顺序)。这意味着该方法可能在某些情况下不起作用,并且类似@NikhilAggarwal所建议的方法更为稳定。
例如:
subCategory
答案 2 :(得分:0)
您可以通过map
子类别filtering
对结果进行分类:
function matches(sub, filters) {
return filters.some(filter => filter.title === sub.title && filter.name === sub.name);
}
const result = categories.map(({ title, subCategories }) => ({ title, subCategories: subCategories.filter(sub => matches(sub, otherCategories)) }));