【问题标题】:How to get all Ids from array embedded within array using Lodash?如何使用 Lodash 从嵌入数组的数组中获取所有 ID?
【发布时间】:2019-07-03 07:20:38
【问题描述】:

我有这个“产品”数组(包含“产品”子文档,每个文档都有自己的唯一 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');

但它只返回 [ ]。

【问题讨论】:

    标签: lodash sub-array subdocument


    【解决方案1】:

    您可以使用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多