如何使用 Lodash get 函数获取嵌套数组对象

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

我需要使用 lodash get 函数在不使用 foreach 的情况下获取对象值数组

"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 payCode ={"PType1","PType2","PType3","PType4"};

我已经使用 lodash get 函数通过类别名称获取值,但不确定如何使用 lodash get 函数获取单个对象中每个类别的支付代码类型

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

改用 Array.map 函数。

const payCodes = paymentTypes.map(o => o.payCode);

我建议使用 Array.flatMap() and Array.map().

的组合

我们将在 PaymentTypes 数组上调用 .flatMap(),然后在 paymentOptions 数组上调用 .map() 以获取所有 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)