如何使用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
相关产品推荐
相关产品推荐

