Utilizing lodash chain to filter and retrieve the parent object

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?

Answer №1

A series is employed to change the form of a framework through multiple stages. In this scenario, maintaining the structure as is desired. By utilizing nested Array.map() (or using lodash's _.map()) functions for iteration and restructuring the framework, while internally employing _.filter() to process the data:

const finances = [{"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":[]}];

const filteredExpenses = finances.map(financial => ({
  ...financial,
  financeElements: financial.financeElements.map(element => ({
    ...element,
    data: _.filter(element.data, { year: '2020' })
  }))
}));

console.log(filteredExpenses);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to dynamically add events to a JQuery FullCalendar using a loop

When utilizing the jQuery full calendar, I need to dynamically set events based on data obtained from a database. To achieve this, I am using data attributes to assign values and then display them on the calendar. Below is an example of my html twig code: ...

What is the best way to retrieve the value of a selected radio button with YUI?

Here is the structure of my radio buttons... <div id="test"> <input name="test1" value="a" type="radio"> <input name="test1" value="b" type="radio"> <input name="test1" value="c" type="radio"> </div> What is the best w ...

Transform the data into put and choose the desired item

Here is the data I am working with "dates": { "contract": [ {"id":1,"name":"1 month","value":false}, {"id":2,"name":"2 months","value":true} ] } I want to display this data in a select dropdown on my HTML page. Here is what I have tried s ...

Having trouble getting the if statement to work for a basic JavaScript toggle feature

The functionality implemented in the resize() function involves checking for the presence of the switch class on the body element. If the class is present, it is removed upon firing the resize function; otherwise, the class is added. However, a problem ar ...

Automatically fill in 'Edit' within an open Dialog using Angular Material

Can you pre-populate and edit a form in Angular Material's openDialog? The form is reactive. The main component has the user's URL with their ID. When the button is clicked, the openDialog should pop up with a populated form based on the passed I ...

Import a precise model from a glb file

Greetings! I am relatively new to working with ThreeJS and just getting the hang of it. After going through some tutorials, I have successfully managed to load glb files and render them in my browser with ease. Recently, I downloaded a GLB file from that ...

The wonders of jQuery popup windows

A code was discovered that displays a popup, but it currently relies on transparency (opacity: 0). I would like to modify it to use display: none instead, as the transparent window in the center of my website is causing issues. Here is the JavaScript code ...

Updating code to insert elements into an array/data structure using Javascript

Hey everyone, I'm new to Javascript and I'm trying to make a change to some existing code. Instead of just returning the count of elements, I want to add each of the specified elements to an array or list. Here is the original code from a Seleni ...

Encountered an error after attempting to submit a form in Node.js - Error message reads: "Cannot

I recently integrated login/registration features into my application. When these features are used in a separate folder, they function perfectly. However, when I added them to my existing application, I encountered an error. The error occurs when I enter ...

Compatibility of HTML5 websites with Internet Explorer

Following a tutorial on HTML5/CSS3, I meticulously followed each step to create a basic website. While the demo of the site worked perfectly in Internet Explorer 8 during the tutorial, my own version did not display correctly when viewed in IE8. I discove ...

Utilize the requestAnimationFrame function to dynamically determine the size and color

My initial goal was to develop a program that generates a circle, gradually shrinking until it vanishes. This circle was supposed to continuously repeat this animation while transitioning between colors (starting from one color and ending in another). Al ...

Firefox experiences failure with Ajax while all other browsers are functioning properly

I've seen discussions on various forums and websites regarding the issue with Firefox browser failing to refresh a CAPTCHA image created in PHP when a button is clicked. I've tried multiple scripts, all of which work perfectly in Edge, Chrome, Sa ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...

What is the best way to extract the text inside a div element based on the input value in a

I attempted to extract the innerText of a div along with the input values within it. For instance: <div> My name is Shubham, I work for <input type="text"/> for the last 5 years.</div> My objective is to retrieve all the text ...

Using CSS to create a background-clip effect on text along with a smooth opacity

I've coded a unique effect for my <h1> heading text where each letter is enclosed in its own <span> element, like this: <h1 class='gradient-heading' id='fade'> <span>H</span> <span>e</span ...

Elevated UI Kit including a setFloating function paired with a specialized component that can accept

I am currently experimenting with using Floating UI alongside various custom React components. These custom components create internal element references for tasks like focus and measurements, but they also have the capability to accept and utilize a RefOb ...

Acknowledging client after client to server POST request has been successfully processed in Node.JS

I've been working on responding to client-side requests with Node.JS. While searching, I came across a helpful article on calling functions on the server from client-side JavaScript in Node JS. However, I'm having trouble implementing it in my pr ...

(React Native) Creating a visually appealing grid layout for displaying an array of item cards

I am working with two arrays named 'word' and 'definition' export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: ...

The vertical overflow feature does not seem to be functioning correctly with the

In the following HTML setup: <div id="container"> <header></header> <div id="content"> <div class="something"></div> <div class="lateralInfo"> <div class="menu"></div> < ...

How to Use Google Tag Manager to Track Forms with Various Choices

Currently, I am facing a challenge in setting up conversion tracking using GTM for a form that offers users multiple options via a drop-down menu. When the user clicks on an option, they are presented with choices like A, B, C, and D. After selecting an ...