Search code examples
javascriptangularlodash

How to use Lodash get function to get the nested array objects


I need to get the array of object values without using foreach by using lodash get function

"PaymentTypes": [
    {
      "categoryName": "Payment Type 1",
      "paymentOptions": [{"payCode": "PType1"}]
    },
    {
      "categoryName": "Payment Type 2",
      "paymentOptions": [{"payCode": "PType2"},{"payCode": "PType3"}]
    },
    {
      "categoryName": "Payment Type 3",
      "paymentOptions": [{"payCode": "PType4"}]
    }
]

I want to have all the paycode in single variable like :

const payCode ={"PType1","PType2","PType3","PType4"};

I have used lodash get function to get values using category name but not sure how to get the paycode type for each category in a single object using lodash get function

const category = get(PaymentTypes,"PaymentOptions");

Solution

  • I'd suggest using a combination of Array.flatMap() and Array.map().

    We'd call .flatMap() on the PaymentTypes array, then call .map() on the paymentOptions array to get all payCodes:

    const obj = { "PaymentTypes": [{ "categoryName": "Payment Type 1", "paymentOptions": [{ "payCode": "PType1"}] }, { "categoryName": "Payment Type 2", "paymentOptions": [{ "payCode": "PType2"}, {"payCode": "PType3"}] }, { "categoryName": "Payment Type 3", "paymentOptions": [{ "payCode": "PType4"}] } ] }
    
    const result = obj.PaymentTypes.flatMap(({ paymentOptions }) => { 
        return paymentOptions.map(({ payCode }) => payCode)
    });
    
    console.log('Result:', result)