JavaScript 如何过滤嵌套数组对象提取所有selected为true的筛选项
嵌套gpo过滤数组实现方案
先对齐原始数据结构
先明确我们要处理的filters结构(避免后续逻辑对齐偏差):
// 原始数据样例 const filters = [ { gpo1: [ { name: '筛选维度1-选项A', selected: true }, { name: '筛选维度1-选项B', selected: false } ], gpo2: [ { name: '筛选维度2-选项C', selected: false }, { name: '筛选维度2-选项D', selected: false } ], gpo3: [ { name: '筛选维度3-选项E', selected: true }, { name: '筛选维度3-选项F', selected: true } ], gpo4: [] } ]
实现逻辑要求
- 对
filters数组逐元素处理,全程不修改原始数据 - 每个元素下的所有gpo对应选项数组,仅保留
selected: true的条目 - 如果某个gpo对应的数组过滤后为空,直接把该gpo键从当前元素中剔除
- 可选:如果某个元素下所有gpo都没有选中条目,把这个空元素从最终数组中移除
方案1:原生JS实现(无依赖)
const selectedFilters = filters // 遍历每个数组元素做处理 .map(filterItem => { // 聚合处理后的gpo键值对 return Object.entries(filterItem).reduce((result, [gpoKey, optionList]) => { // 过滤当前gpo下选中的选项 const selectedOptions = optionList.filter(option => option.selected) // 有选中内容才保留这个gpo键 if (selectedOptions.length) { result[gpoKey] = selectedOptions } return result }, {}) }) // 可选:剔除所有gpo都为空的空对象元素 .map(processedItem => Object.keys(processedItem).length ? processedItem : null) .filter(Boolean)
方案2:Lodash实现(匹配原有技术栈)
之前用lodash没得到预期结果,大概率是漏了对每个gpo下选项数组的二次过滤,或者把空的gpo键也保留了。下面是可用的实现:
import { map, mapValues, filter, pickBy, isEmpty } from 'lodash' const selectedFilters = map(filters, filterItem => { // 先对每个gpo的选项数组做过滤,只留选中项 const processedGpo = mapValues(filterItem, optionList => filter(optionList, ['selected', true])) // 把过滤后为空的gpo键剔除 return pickBy(processedGpo, gpoList => !isEmpty(gpoList)) }) // 可选:剔除全空的对象元素 .filter(processedItem => !isEmpty(processedItem))
按照前面的原始数据样例,最终生成的
selectedFilters结构为:
[ { gpo1: [{ name: '筛选维度1-选项A', selected: true }], gpo3: [ { name: '筛选维度3-选项E', selected: true }, { name: '筛选维度3-选项F', selected: true } ] } ]
其中gpo2因为所有选项都未选中、gpo4本身为空数组,都没有纳入最终结果。
内容的提问来源于stack exchange,提问作者aloredo
相关产品推荐
相关产品推荐

