You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用Lodash或JavaScript过滤数组对象,保留isChecked为true的子项并移除无符合条件子项的父对象

如何过滤商品数据,保留选中项并移除无选中项的卖家?

我来帮你解决这个问题!你需要同时完成两个核心操作:一是对每个卖家的商品列表,只保留isChecked为true的商品;二是移除那些没有任何选中商品的卖家。下面分别用原生JavaScript和Lodash来实现:

原生JavaScript实现

原生JS可以通过map和filter的组合完成需求,逻辑清晰直观:

  1. 先用map遍历每个卖家对象,复制原对象并替换item数组为过滤后的选中项;
  2. 再用filter去掉处理后item数组为空的卖家。
const originalData = [
  { sellerId: "seller1", name: "Nike", item: [{ id: "xxx1", isChecked: false, price: "719700.00", productName: "product a", quantity: 2 }, { id: "xxx2", isChecked: true, price: "219700.00", productName: "product b", quantity: 1 }] },
  { sellerId: "seller2", name: "Adidas", item: [{ id: "xxx1", isChecked: false, price: "49700.00", productName: "product x", quantity: 1 }, { id: "xxx2", isChecked: true, price: "4700.00", productName: "product y", quantity: 5 }] }
];

const filteredData = originalData
  // 处理每个卖家的商品列表,只保留选中项
  .map(seller => ({
    ...seller, // 复制卖家的原有属性
    item: seller.item.filter(item => item.isChecked === true)
  }))
  // 过滤掉没有选中商品的卖家
  .filter(seller => seller.item.length > 0);

console.log(filteredData);

Lodash实现

用Lodash的链式调用可以让代码更简洁,结合_.map和_.filter就能高效完成需求:

const _ = require('lodash');

const originalData = [
  { sellerId: "seller1", name: "Nike", item: [{ id: "xxx1", isChecked: false, price: "719700.00", productName: "product a", quantity: 2 }, { id: "xxx2", isChecked: true, price: "219700.00", productName: "product b", quantity: 1 }] },
  { sellerId: "seller2", name: "Adidas", item: [{ id: "xxx1", isChecked: false, price: "49700.00", productName: "product x", quantity: 1 }, { id: "xxx2", isChecked: true, price: "4700.00", productName: "product y", quantity: 5 }] }
];

const filteredData = _.chain(originalData)
  // 处理每个卖家的商品列表,筛选isChecked为true的项
  .map(seller => ({
    ...seller,
    item: _.filter(seller.item, { isChecked: true })
  }))
  // 移除item为空的卖家
  .filter(seller => !_.isEmpty(seller.item))
  .value(); // 执行链式操作并返回结果

console.log(filteredData);

为什么你原来的Lodash代码不生效?

你写的_.filter(data, { item: [{ isChecked: false }] })逻辑完全不符合需求:

  • 这个写法是在查找商品列表中包含至少一个isChecked为false的商品的卖家,和你要保留选中项的目标完全相反;
  • 它只是筛选卖家,不会修改卖家的item数组,自然无法移除未选中的商品。

内容的提问来源于stack exchange,提问作者Rio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:37:33