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

如何使用Lodash从嵌套结构数组中提取所有Product Id?

解决Lodash提取数组中子文档id的问题

嘿,我来帮你搞定这个问题~你写的代码返回空数组,核心原因是搞错了访问层级:this.Products是一个数组,不是单个对象,你直接写this.Products.Product相当于从数组本身去拿Product属性,这显然不存在,所以返回空数组啦。

正确的实现方法

这里有几种靠谱的写法,都能得到你想要的filterIds:

1. Lodash简化路径写法(最简洁)

直接通过字符串路径指定要提取的属性,Lodash会自动遍历数组中的每个元素,深入到子文档取id:

const filterIds = _.map(this.Products, 'Product.id');

2. Lodash回调函数写法(更灵活)

如果后续需要对元素做额外处理,用回调函数的方式更直观:

const filterIds = _.map(this.Products, (item) => item.Product.id);

3. 原生JS写法(无需Lodash)

其实不用Lodash,原生JS的Array.map()也能轻松实现,语法差不多:

const filterIds = this.Products.map((item) => item.Product.id);

测试验证

用你提供的示例数据测试一下:

const Products = [
  { listPrice: '1.90', Product: {id: 'xxx1'} },
  { listPrice: '3.90', Product: {id: 'xxx2'} },
  { listPrice: '5.90', Product: {id: 'xxx3'} }
];

// 用Lodash的写法
const filterIds = _.map(Products, 'Product.id');
console.log(filterIds); // 输出: ['xxx1', 'xxx2', 'xxx3']

这样就能得到你想要的结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:27:33