如何使用 Lodash 从嵌入数组的数组中获取所有 ID?
How to get all Ids from array embedded within array using Lodash?
我有这个 'Products' 数组(包含 'Product' 个子文档,每个子文档都有自己唯一的 ID):
Products: [
{ listPrice: '1.90', Product: {id: 'xxx1'} },
{ listPrice: '3.90', Product: {id: 'xxx2'} },
{ listPrice: '5.90', Product: {id: 'xxx3'} }
]
我想使用 Lodash 得到以下结果:
filterIds = ['xxx1', 'xxx2', 'xxx3'];
在我的代码中,我是这样写的:
filterIds = _.map(this.Products.Product, 'id');
但它只是 returns [ ].
您可以像这样使用 vanilla JS 的 Array.prototype.map 方法来做到这一点:
const arr = [{listPrice:'1.90',Product:{id:'xxx1'}},{listPrice:'3.90',Product:{id:'xxx2'}},{listPrice:'5.90',Product:{id:'xxx3'}}],
filtered = arr.map(obj => obj.Product.id);
console.log(filtered);
如果必须使用lodash:
const arr = [{listPrice:'1.90',Product:{id:'xxx1'}},{listPrice:'3.90',Product:{id:'xxx2'}},{listPrice:'5.90',Product:{id:'xxx3'}}],
res = _.map(arr, obj => obj.Product.id);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
在 Lodash 中
const _ = require('lodash');
const Products= [
{ listPrice: '1.90', Product: {id: 'xxx1'} },
{ listPrice: '3.90', Product: {id: 'xxx2'} },
{ listPrice: '5.90', Product: {id: 'xxx3'} }
]
console.log(_.map(_.map(Products, 'Product'), 'id'));
//[ 'xxx1', 'xxx2', 'xxx3' ]
我有这个 'Products' 数组(包含 'Product' 个子文档,每个子文档都有自己唯一的 ID):
Products: [
{ listPrice: '1.90', Product: {id: 'xxx1'} },
{ listPrice: '3.90', Product: {id: 'xxx2'} },
{ listPrice: '5.90', Product: {id: 'xxx3'} }
]
我想使用 Lodash 得到以下结果:
filterIds = ['xxx1', 'xxx2', 'xxx3'];
在我的代码中,我是这样写的:
filterIds = _.map(this.Products.Product, 'id');
但它只是 returns [ ].
您可以像这样使用 vanilla JS 的 Array.prototype.map 方法来做到这一点:
const arr = [{listPrice:'1.90',Product:{id:'xxx1'}},{listPrice:'3.90',Product:{id:'xxx2'}},{listPrice:'5.90',Product:{id:'xxx3'}}],
filtered = arr.map(obj => obj.Product.id);
console.log(filtered);
如果必须使用lodash:
const arr = [{listPrice:'1.90',Product:{id:'xxx1'}},{listPrice:'3.90',Product:{id:'xxx2'}},{listPrice:'5.90',Product:{id:'xxx3'}}],
res = _.map(arr, obj => obj.Product.id);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
在 Lodash 中
const _ = require('lodash');
const Products= [
{ listPrice: '1.90', Product: {id: 'xxx1'} },
{ listPrice: '3.90', Product: {id: 'xxx2'} },
{ listPrice: '5.90', Product: {id: 'xxx3'} }
]
console.log(_.map(_.map(Products, 'Product'), 'id'));
//[ 'xxx1', 'xxx2', 'xxx3' ]