如何用JavaScript过滤排除特定空数组条件的对象数组?
问题:过滤JavaScript对象数组的特定条件项
需要过滤掉同时满足以下两个条件的对象:
productType数组中每个对象的itemTypes均为空数组- 对象自身的
itemTypes数组也为空
输入数据
const input = [ { id: '1', productType: [ { id: '2', itemTypes: [ { id: '3', }, ], }, ], itemTypes: [ { id: '4', } ], }, { id: '2', productType: [ { id: '7', itemTypes: [ { id: '8', }, ], }, { id: '9', itemTypes: [], }, ], itemTypes: [ { id: '5', }, { id: '6', }, ], }, { id: '9', productType: [ { id: '11', itemTypes: [], }, ], itemTypes: [], }, ];
我的尝试
const output = input.filter(e => e.includes(!isEmpty(productTypes.itemTypes) && !isEmpty(itemTypes));
遇到的问题:productType是数组,不知道如何检查其中每个对象的itemTypes是否都为空数组。
解决方案
可以利用数组的every方法来检查productType中所有对象的itemTypes是否都为空,再结合自身itemTypes的判断,最终实现过滤:
const output = input.filter(e => { // 判断productType中每个对象的itemTypes都为空数组 const allProductItemsEmpty = e.productType.every(type => type.itemTypes.length === 0); // 判断自身的itemTypes为空数组 const ownItemsEmpty = e.itemTypes.length === 0; // 过滤掉同时满足两个条件的对象,保留其余对象 return !(allProductItemsEmpty && ownItemsEmpty); });
代码说明
every方法会遍历productType数组,只有当数组中所有元素都满足type.itemTypes.length === 0时,才返回true,正好符合“每个对象的itemTypes均为空”的判断需求。- 最终返回的是对“两个条件同时成立”的取反,这样就能保留不满足过滤条件的对象,得到期望的输出。
验证输出
const output = [ { id: '1', productType: [ { id: '2', itemTypes: [ { id: '3', }, ], }, ], itemTypes: [ { id: '4', } ], }, { id: '2', productType: [ { id: '7', itemTypes: [ { id: '8', }, ], }, { id: '9', itemTypes: [], }, ], itemTypes: [ { id: '5', }, { id: '6', }, ], }, ];
内容的提问来源于stack exchange,提问作者stackuser
相关产品推荐
相关产品推荐

