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

Is there a workaround for the React useContext issue in Typescript aside from using <Partial>?

I am currently working on a React app that utilizes the useContext hook, but I am facing challenges with correctly typing my context. Here is the code snippet in question: import React, { useState, createContext } from 'react'; import endpoints f ...

Unauthorized Access: JWT Express API fails to authenticate the HTTPInterceptor header

I've been working on integrating JWT Middleware in ExpressJS with the following implementation: const authenticateJWT = (req, res, next) => { const authHeader = req.headers.authorization; ... }; and also an HTTPInterceptor implementation i ...

Enhance your React application by using a personalized hook that allows you to trigger a function

After creating a custom hook to handle uploads to an AWS S3 bucket, I encountered a small issue. Rather than having the hook execute the logic directly, I decided to create an executable function to return instead. However, I am facing a problem where the ...

The firebase.d.ts on iOS functions properly, whereas on Android, it becomes

Currently, I am working with Ionic 2 on my Mac system. Your system information: Cordova CLI: 6.4.0 Ionic Framework Version: 2.0.0-rc.4 Ionic CLI Version: 2.1.18 Ionic App Lib Version: 2.1.9 Ionic App Scripts Version: 1.0.0 ios-deploy version: Not instal ...

Purge the inversify-js container and fetch fresh service instances

My frontend application in react-native utilizes inversify-js for service classes. I have implemented an IOC structure where services are shared as singleton instances, each with an init/destroy method to manage internal state. While the init/destroy mec ...

Struct object not found within nested array during JSON unmarshaling

Encountered an issue with unmarshalling a string back to a struct object that contains a nested array of struct objects. The problem is demonstrated in the following code snippet: The JSON string is as follows: const myStr = `{ "name": "test_session1", ...

hosting on a base URL does not activate cloud functions

meta-tags-are-not-updating-for-root-url-www-domain-com Base url not triggered hosting I encountered a similar issue as mentioned in the first link above. The solutions provided seemed unusual, like having to delete index.html every time I build/deploy my ...

Utilize the ngClass directive in conjunction with ngFor loop functionality

Currently, I am working on rendering a list of elements using the *ngFor directive in Angular. However, I have encountered an issue where only certain parts of the text within the list items should be bold based on specified requirements. I attempted to ac ...

Encountering "module not found" errors while working on an Angular 2 project using the angular2-seed starter pack

Recently, I upgraded to the latest version and integrated SASS according to the guidelines provided here: https://github.com/mgechev/angular2-seed/wiki/Enabling-SASS-support However, upon running npm start, I encountered a series of errors: [18:07:51] & ...

What is the process of accessing the changelog.md file within a component in Angular?

My challenge is to showcase the content from my changelog.md file, which is situated at the same level as the package.json file. I created a service for this purpose using the following code, function getData() { return http.get('../c ...

Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server This is the form structure I have implemented: this.userform = this._formbuilder.group({ email: ['', [Validators.requir ...

The module imported by Webpack appears to be nothing more than a blank

I am attempting to integrate the "virtual-select-plugin" library into my Typescript project using webpack. Unfortunately, this library does not have any type definitions. Upon installation via npm, I encountered the following error in the browser: TypeErro ...

Iterating through a JSON object that contains an array nested within another array using PHP foreach loop

Below is a snippet from a json file: { "status": { "http_code": 200 }, "contents": [ { "FabrikatNavn": "Jaguar", "ModelNavn": "420G", "PrisDetailDkk": 119900, "StatusTyper": [ { "StatusId": -5, ...

Get an angular xml file by utilizing the response from a C# web API download

I am trying to download an XML file from a database using a Web API in C#, which returns the file as byte[]. How can I properly read these bytes and convert them into an XML file on the client side using Angular? Despite attempts with blobs and other metho ...

Issue with Angular 7: "Unspecified name attribute causing control not found"

As I delve into the creation of my initial Angular application, I find myself faced with a series of errors appearing in the development mode console: ERROR Error: "Cannot find control with unspecified name attribute" ERROR Error: "Cannot f ...

During the process of adding a new template to my Angular project, I came across an issue within the core.min.js and script.js files

index.html <html class="wide wow-animation" lang="en"> <body> <app-root></app-root> <!-- Javascript--> <script src="assets/js/core.min.js"></script> <script src="assets/js/script.js"></script& ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

What is the best way to display the information stored in a nested JSON hash table onto a PowerShell output?

Is there a way to output all the contents of a nested JSON hash table in PowerShell in a single line? $json = @" { "outer": "value1", "outerArray": [ "value2", "value3" ], "outerHash": { "inner": "value4", " ...

Verify internet connectivity with Ionic

Seeking a reliable method to accurately detect whether a mobile device is truly online and connected to the internet. One approach I have explored involves utilizing an http interceptor: if (navigator.connection.type != Connection.NONE) alert("you'r ...

The ts-mocha test does not play well with the use of node-fetch library

I have set up ts-mocha and node-fetch to run a unit test, but I am encountering the following error: TypeError: Unknown file extension ".ts" for ... The content of the file is as follows: import fetch from 'node-fetch'; export defau ...