What is the best way to split a single object into two separate objects based on a specific value within the object using lodash?

Imagine a scenario with an object containing two channels in Dutch (NL) language and one channel in English (EN) language:

[
    {
        "name": "De Redactie",
        "channels": [
            {
                "name": "headlines",
                "pubDate": "2017-05-15 09:15:00",
                "language": "nl",
                "items": [

                ]
            },
            {
                "name": "headlines English",
                "pubDate": "2017-05-14 18:05:00",
                "language": "en",
                "items": [

                ]
            },
            {
                "name": "politiek",
                "pubDate": "2017-05-14 20:11:00",
                "language": "nl",
                "items": [

                ]
            }
        ]
    }
]

How can I rearrange them to achieve this desired outcome:

[
    {
        "name": "De Redactie",
        "channels": [
            {
                "name": "headlines",
                "pubDate": "2017-05-15 09:15:00",
                "language": "nl",
                "items": [

                ]
            },
            {
                "name": "politiek",
                "pubDate": "2017-05-14 20:11:00",
                "language": "nl",
                "items": [

                ]
            }
        ]
    },
    {
        "name": "De Redactie",
        "channels": [
            {
                "name": "headlines English",
                "pubDate": "2017-05-14 18:05:00",
                "language": "en",
                "items": [

                ]
            }
        ]
    }
]

Please note that the data provided is for illustration purposes. The actual data may have multiple entries of different languages.

I have attempted to solve this using lodash functions and complex forEach loops, but haven't found the right approach yet.

An ideal solution would be utilizing lodash or typescript, considering I am working within Angular 4 environment.

Answer №1

Loop through the array using Array#map. Extract the channel arrays for each object by utilizing object destructuring along with object rest syntax. Traverse through the channels via Array#reduce, grouping channels based on language into a Map. Convert it back to an array by spreading the iterator of Map's values.

Generate an array of objects by mapping them and setting the group as the channels property of the object. Flatten the array by spreading into Array#concat:

const data = [{"name":"De Redactie","channels":[{"name":"headlines","pubDate":"2017-05-15 09:15:00","language":"nl","items":[]},{"name":"headlines English","pubDate":"2017-05-14 18:05:00","language":"en","items":[]},{"name":"politiek","pubDate":"2017-05-14 20:11:00","language":"nl","items":[]}]}];

const result = [].concat(...data.map(({ channels, ...rest }) => {
  const channelGroups = [...channels.reduce((m, channel) => {
    m.has(channel.language) || m.set(channel.language, []);
    m.get(channel.language).push(channel);
  
    return m;
  }, new Map()).values()];
  
  return channelGroups.map((channels) => ({
    ...rest,
    channels
  }));
}));

console.log(result);

Answer №2

Here is a way to achieve the same result using lodash:

const result = _.chain(arr)
    .flatMap(item => _.map( // retrieve array of channels with parent name
        item.channels,
        channel => _.assign({}, channel, { parentName: item.name })
    ))
    .groupBy('language') // group channels by language
    .values() // obtain arrays of channels for each language
    .map(langArrs => ({ // create final structure
        name: _.first(langArrs).parentName, // get name for language channels
        channels: _.omit(langArrs, ['parentName']) // exclude parent name from channels
    }))
    .value();

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

The PWA application is experiencing crashes on Safari following the recent IOS 17 update

Recently, I encountered an issue with my Angular app functioning as a PWA on my iPhone. Everything was working smoothly until the latest iOS 17 update. Now, the app crashes frequently and even when I clear the cache on Safari, it only works for a few min ...

Reactive form within a form

I am working on an angular application that involves a nested reactive form. I would appreciate it if you could review my method of nesting the form by passing the parent form reference in the child component and let me know if this approach is appropria ...

Angular EventEmitter fails to emit event

I am currently working with an Angular vertical stepper (using Angular Material) consisting of separate components for each step, with a parent component calling all these child components. My challenge is in passing data between the parent and child compo ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

Querying Multipolygons in Ruby on Rails using PostGIS

When querying my PostGIS database for districts, I receive the following output in my LatLon column: SELECT id, ST_AsText(latlon) AS geom FROM district; MULTIPOLYGON(((16.4747103091463 48.2753153528078,16.4744319731163 48.275314069121,16.4743511374383 48 ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

Enhance your Angular app by dynamically adding classes to existing classes on a host component

How can I dynamically add a class to the host component of this angular component? @Component({ selector: 'test', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'], encapsulation: ViewEncapsulation ...

I encountered a conflict with the FOREIGN KEY constraint while attempting to execute the INSERT statement in the frontend application. However, the same statement successfully runs

I am currently developing a project using Angular for the frontend (Visual Studio Code) and .NET Core for the backend (Visual Studio). Everything seems to be functioning perfectly when I test the backend endpoints with Postman. However, I encountered an i ...

Adding cache to Observable in mat-autocomplete can improve performance by reducing redundant API calls

I have successfully implemented a mat-autocomplete feature. However, I am facing an issue where the Http call is triggered with every keyup event, such as 'r', 'ra', 'ram', 'rame', 'ramesh'. This frequent u ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Unable to access Angular 6 Application running on AWS EC2 instance via public IP address

Encountering difficulties accessing an Angular 6 application via public IP over the internet. To troubleshoot, I initiated a Windows EC2 instance and proceeded to install Node.js and Angular CLI by executing the following commands- npm install -g @angular ...

There is no corresponding version available for [email protected] in Angular 6

After cloning a project from git, I attempted to run npm install. However, an error message popped up, as shown in the following link: https://i.stack.imgur.com/pqYbK.png Can someone please explain why this is happening and how I can resolve it? Any help ...

How can I effectively build an Angular Library containing various components?

I am currently restructuring the core elements that form a search page into an angular library. My goal is to include various components in this angular library, such as SearchControls, PageHeader, PageFooter, and more. I intend to insert <search-contro ...

Encountering issues when verifying the ID of Angular route parameters due to potential null or undefined strings

Imagine going to a component at the URL localhost:4200/myComponent/id. The ID, no matter what it is, will show up as a string in the component view. The following code snippet retrieves the ID parameter from the previous component ([routerLink]="['/m ...

Transmitting data from Angular to .NET Core for seamless integration

I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work... Below is my component where I call my service upon button click: handleFileInput(file: FileList) { this. ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books. public getBooks(): Observable<Book[]>{ ...