I am trying to utilize the Lodash chain function to filter through nested array items within an array and then return the full parent object.
Let me share some dummy data that outlines the scenario I am facing:
const capital = [
{
"financeCategory": "Loans",
"financeCategoryId": "22HM6fFFwx9eK2P42Onc",
"financeElements": [
{
"financeCategoryId": "22HM6fFFwx9eK2P42Onc",
"financeElementId": "JQiqqvGEugVQuI0fN1xQ",
"financeElementTitle": "Convertible loan",
"data": [
{
"month": 1,
"value": 100,
"year": "2020"
},
{
"month": 1,
"value": 100,
"year": "2019"
},
],
}
]
},
{
"financeCategory": "Investments",
"financeCategoryId": "JtnUsk5M4oklIFk6cAlL",
"financeElements": []
},
{
"financeCategory": "Ownerships Contribution",
"financeCategoryId": "PaDhGBm5uF0PhKJ1l6WX",
"financeElements": []
}
];
The objective is to filter the "data" array within financeElements and return the complete expense object with the applied filter on "data".
For example, let's say I want to extract only the data from financeElements where the year is 2020. My attempt so far has been:
const expenseFiltered: any = _.chain(expenses)
.flatMap('financeElements')
.flatMap('data')
.filter({year: '2020' as any}).value();
However, this code snippet only gives back the filtered "data" objects rather than the entire object. The output looks like this:
[{
"month": 1,
"value": 100,
"year": "2020"
}]
While there are alternate methods to achieve the desired result, I'm keen on achieving this with a simple _.chain command. Is it possible to accomplish this using lodash chain?