Utilizing the `map` function for converting a `forEach`

I'm currently in the process of refactoring my code to use the map function instead of forEach. However, I am facing an issue with implementing a null check for order.FunctionStatusList while using map. Specifically, I need guidance on how to handle the else statement when dealing with orderAction.OrderList.

Below is the original code using forEach:

        this.orders.forEach((order: Order) => {
            let orderAction: OrderAction = new OrderAction();
            orderAction.FunctionTypeCode = this.functionTypeCode;
            orderAction.SelectedAction = this.actionSelected;
            if (order.FunctionStatusList != null) {
                order.FunctionStatusList.forEach(orderFunctionStatus: OrderFunctionStatus  => {
                    orderAction.OrderList = [{
                        OrderId: order.OrderId,
                        AvailableActions: orderFunctionStatus.AvailableActions,
                        IsAvailableActions: orderFunctionStatus.AvailableActions.length > 0,
                        ValidationMessage: OrderFunctionStatus.ValidationMessage
                    }];
                });
            }
            else {
                orderAction.OrderList = [{
                    OrderId: order.OrderId,
                    AvailableActions: [],
                    IsAvailableAction: false,
                    ValidationMessage: ''
                }];
            }
            this.orderActionList.push(orderAction);
        });

And here is the updated code utilizing map:

            this.orderActionList = this.orders.map(order => ({
            FunctionTypeCode: this.functionTypeCode,
            SelectedAction: this.actionSelected,
            OrderList: order.FunctionStatusList ? order.FunctionStatusList.map((orderFunctionStatus: OrderFunctionStatus) => ({
                OrderId: order.OrderId,
                AvailableActions: orderFunctionStatus.AvailableActions,
                IsAvailableAction: orderFunctionStatus.AvailableActions.length > 0,
                ValidationMessage: orderFunctionStatus.ValidationMessage
            })):[]
        })

|EDIT| Additionally, see below the json format for the order:

{
    "OrderId": "1",
    "FunctionStatusList": [{
        "FunctionTypeCode": "1",
        "AvailableActions": [{
            "ActionLabel": "1",
            "ActionValue": "1"
        }]
    }]
 }

Lastly, here is the expected JSON structure for order-action:

    {
"FunctionTypeCode": "1",
"SelectedAction: "1",
"OrderList": [{
   "OrderId": "1",
   "IsAvailableActionsLoaded": "1",
   "AvailableActions": [{
      "ActionLabel": "1",
      "ActionValue": "1"
   }]
}]

}

Answer №1

Indeed, you were on the right track and all that was required was to incorporate the else clause into your code, specifying the properties following the colon.

You managed to solve it in a very graceful manner. Using the ternary operator allowed for creating an inline if... else statement with the conditions you needed.

As I worked on the code in pure JS, I omitted the .this and type assertions, so please excuse those absences.

I have introduced a new property called ValidationMessage to the provided code sample. Additionally, by using a ternary operator, you can easily check if it holds a truthy value. If not, you can simply add ''.

Just to note, I assumed that you are retrieving the values of functionTypeCode and actionSelected from external sources, which is why I defined them as constants within the function.

const orderActionFormatter = (input) => {
    const functionTypeCode = 1;
    const actionSelected = 1;
    return input.map(order => {
        return ({
            FunctionTypeCode: functionTypeCode,
            SelectedAction: actionSelected,
            OrderList: order.FunctionStatusList != null ? order.FunctionStatusList.map(orderFunctionStatus => {
                return ({
                    OrderId: order.OrderId,
                    AvailableActions: orderFunctionStatus.AvailableActions,
                    IsAvailableAction: orderFunctionStatus.AvailableActions.length > 0,
                    ValidationMessage: !!orderFunctionStatus.ValidationMessage ? orderFunctionStatus.ValidationMessage : ''
                })
            }) : {
                OrderId: order.OrderId,
                AvailableActions: [],
                IsAvailableAction: false,
                ValidationMessage: ''
            }
        })
    })
}

const input = [{"OrderId":"1","FunctionStatusList":[{"FunctionTypeCode":"1","AvailableActions":[{"ActionLabel":"1","ActionValue":"1"}],"ValidationMessage":"foo bar"}]}];
const inputNullFunctionStatusList = [{"OrderId":"1","FunctionStatusList":null}]

 console.log(orderActionFormatter(input))
 console.log(orderActionFormatter(inputNullFunctionStatusList))

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

Error: The System variable is not defined in the current context - Angular 2

Recently, I updated my angular version and now I am encountering errors in the console that are preventing my application from running smoothly. Despite having no errors in my terminal, this issue has been persisting for days and I can't seem to find ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am ...

Trouble viewing Three.js content in Index.html

My current project involves building a website using three.js with typescript. However, I am facing an issue where only the header from my index.html file is displayed when I try to load the website onto a local server. The main problem arises when I atte ...

Is it possible to specify the version of a dependency using Stackblitz?

Is it possible to specify the dependency version on StackBlitz? I recently updated the dependency on NPM, however StackBlitz seems to be stuck on installing the old version. ...

Utilize the TypeScript Compiler API to extract the Type Alias Declaration Node from a Type Reference Node

Currently, I am utilizing ts-morph library which makes use of the TS Compiler API. Here is an example of my code: export type Foo = string export const foo: Foo = 'bar' Whenever I try to find the type for the export of foo, it returns string. H ...

There is no correlationId found within the realm of node.js

Currently, I am in the process of implementing correlationId functionality using express-correlation-id. I am diligently following the guidelines provided on this page: https://www.npmjs.com/package/express-correlation-id. I have successfully imported the ...

The element access has been upgraded to utilize ng-content

I attempted to create a tabs component that could be used similarly to Angular Material Component. However, the solution I came up with was flawed and buggy. In this attempt, I utilized document.getElementsByTagName('app-tab'). This is the temp ...

Diverse Selection of Font Awesome Icons

In my React project with TypeScript, I have a header component that accepts an Icon name as prop and then renders it. I am trying to figure out the best way to ensure that the icon prop type matches one of the existing FontAwesome Icons. import { FontAwe ...

The content displayed in the PrimeNG p-table is limited to only the table name with no additional information

After upgrading Angular to version 9, I switched from p-dataTable to p-table in PrimeNG. With a table named users, I intended to display them on the screen upon rendering the view using the following HTML: users = ['one','two','thr ...

What are the benefits of incorporating NgRx in Angular, even when data is consistently synchronized through two-way data binding?

NgRx, analogous to Redux in React, is a tool used for state management in Angular. While state management can become convoluted in React projects, Angular typically avoids this issue thanks to its two-way data binding synchronization. Interestingly, many ...

Error encountered numerous times within computed signals (angular)

I have incorporated signals into my Angular application. One of the signals I am using is a computed signal, in which I deliberately introduce an exception to see how it is handled. Please note that my actual code is more intricate than this example. pu ...

Element not recognized: <my-company-form-extra> - have you properly registered this component?

I've been attempting to render a component using the is directive <template> <div> <v-tabs v-model="currentTab" fixed-tabs> <v-tab v-for="(item, i) in tabItems" :key="i">{{ item }} < ...

Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc. The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening? To investigate the issue, I tested my ...

Testing an action within an interval in Angular using Jasmine

Looking to run a jasmine test on this method: public init(): Subscription { return interval(100).subscribe(() => this.doSomething()) } The goal is to verify that the doSomething method gets executed when the init function is called. We are usi ...

Postman issue: Your username and password combination is incorrect within the MEAN stack environment

I am new to mean stack development and facing some issues. When I try to run "api/users/login" in Postman, it shows an error saying "Username or password is invalid!". Additionally, when attempting to register using "register/users/register", it gives a me ...

When attempting to activate the same route, the Angular 8 router fails to trigger any events when utilizing `onSameUrlNavigation: 'reload'`

Router configuration: imports: [ RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload', scrollPositionRestoration: 'top' }) ], Defined route: { path: 'orders', loadChildren: './ ...

The useRef function is malfunctioning and throwing an error: TypeError - attempting to access 'filed2.current.focus' when 'filed2' is null

I'm attempting to switch focus to the next input field whenever the keyboard's next button is pressed. After referring to the react native documentation, it seems that I need to utilize the useRef hook. However, when following the instructions f ...

Displaying multiple lines of text in a MatSnackbar in Angular is possible

For instance: let message: example;let message2 : example3; For Example: alert(message + '\n'+ message2); Is it possible to display the mat snackbar in Angular in a similar way as shown above?                     ...

Is it possible to subscribe multiple times in Angular without triggering multiple requests?

I have a service call in Angular that caches its response like so: public cacheMyServiceResponse(): Observable<any> { return this.appConfig.getEndpoint('myService') .pipe( switchMap((endpoint: Endpoint) => this.http.get(endp ...

"String representation" compared to the method toString()

Currently, I am in the process of writing unit tests using jasmine. During this process, I encountered an issue with the following code snippet: let arg0: string = http.put.calls.argsFor(0) as string; if(arg0.search(...) This resulted in an error stating ...