Search code examples
lodashsub-arraysubdocument

How to get all Ids from array embedded within array using Lodash?


I have this 'Products' array (contain 'Product' sub documents, each with its own unique Id):

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

I want to get this result below using Lodash:

filterIds = ['xxx1', 'xxx2', 'xxx3'];

In my code, this is what I wrote:

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

But it just returns [ ].


Solution

  • You can do this using vanilla JS's Array.prototype.map method like so:

    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);

    If you must use 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>