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");
CodePudding user response:
Use the Array.map function instead.
const payCodes = paymentTypes.map(o => o.payCode);
CodePudding user response:
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)