Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through.

const monthObject = {
    "March 2022": [
        {
            "date": "2022-03-16",
            "amount": "-50",
            "description": "mar ",
            "category": "Salary",
            "createdAt": "2022-04-15T06:27:16.953Z",
            "updatedAt": "2022-04-15T06:27:16.953Z",
            "__v": 0
        }
    ],
    "April 2022": [
        {
            "date": "2022-04-15",
            "amount": "100",
            "description": "apr",
            "category": "Debt",
            "createdAt": "2022-04-15T06:27:02.381Z",
            "updatedAt": "2022-04-15T06:27:02.381Z",
            "__v": 0
        },
        {
            "date": "2022-04-19",
            "amount": "-150",
            "description": "apr",
            "category": "Salary",
            "createdAt": "2022-04-15T06:27:33.035Z",
            "updatedAt": "2022-04-16T11:48:39.540Z",
            "__v": 0
        },
        {
            "date": "2022-04-26",
            "amount": "11",
            "description": "asd",
            "category": "Credit",
            "createdAt": "2022-04-15T18:03:24.785Z",
            "updatedAt": "2022-04-16T11:51:49.503Z",
            "__v": 0
        },
        {
            "date": "2022-04-27",
            "amount": "111",
            "description": "asdad",
            "category": "Debt",
            "createdAt": "2022-04-19T13:59:30.821Z"
            "updatedAt": "2022-04-19T13:59:30.821Z",
            "__v": 0
        }
    ],
    "May 2022": [
        {
            "date": "2022-05-18",
            "amount": "-200",
            "description": "may",
            "category": "Salary",
            "createdAt": "2022-04-15T06:27:42.184Z",
            "updatedAt": "2022-04-15T06:27:42.184Z",
            "__v": 0
        }
    ],
    "June 2022": [
        {
            "date": "2022-06-22",
            "amount": "290",
            "description": "aaa",
            "category": "Investments",
            "createdAt": "2022-04-16T12:29:27.857Z",
            "updatedAt": "2022-04-16T12:29:27.857Z",
            "__v": 0
        }
    ]
}

I initially accessed them using direct methods like:

this.monthlyCategories = Object.entries(this.monthlyObject)
.map((arrForEachMonth: Array<any>) => {
  return arrForEachMonth[1]
  .map((item: any) => item.category);
});

This method was functional, but I wanted to avoid code repetition by passing a function argument as the mapped value (item.name). However, the result turned out to be undefined. Could you please point out what error I might have made?

const monthObjEntries = (name: string) => Object
  .entries(this.monthlyObject)
  .map((arrForEachMonth: Array<any>) => {
    
    return arrForEachMonth[1]
    .map((item: any) => item.name) // <- the problem lies here and returns undefined
})

console.log(monthObjEntries('amount'));

After reflection, I realized that the argument name is not being passed correctly to item.name. I'm unsure about how to resolve this issue...

Answer №1

In order to access the correct property, you need to utilize item[name]. If not, it will mistakenly attempt to retrieve the property name of item, which is non-existent.

return arrForEachMonth[1]
    .map((item: any) => item[name])

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

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...

Ordering a list of IP addresses using Angular Material table sorting

Here is an example I am baffled by the fact that Material Table sorting does not properly arrange the table. I have created a stackblitz example to demonstrate this. Expected order - Sorting lowest IP first: "10.16.0.8" "10.16.0.16" & ...

I'm having trouble extracting data into my HTML file using the append function in Jquery. What could be causing this issue?

Hey there, I'm having some trouble extracting data from a URL to my HTML file using jQuery. Can anyone help out? I'm still new to this. Here's the code <html> <head> <title> My Program </title> <script src="ht ...

Leaflet OSM: Adjust map focus to the polygon's center

Looking to create an HTML file that integrates the Leaflet library to display an OpenStreetMap view with a centered polygon? I've been following a helpful discussion, but still unsure about how to center and autozoom an arbitrary polygon on the map. A ...

Adding scripts to a PartialView in MVC using Jquery's append function

My issue is with a JavaScript function that appends a PartialView into a div. Everything seems to work correctly, except for the fact that the PartialView contains some scripts enclosed within <script></script> tags. As a result, when these dyn ...

The issue with Angular JS is that it fails to refresh the select and input fields after selecting a date

Currently utilizing Angular JS and Bootstrap, I have a query regarding updating the input for a datepicker calendar and a select from a function. The values are being successfully updated, however, they do not reflect on their respective inputs. It seems ...

Django: Is there a way to modify the PayPal script for pay upon arrival?

I currently do not wish to accept online payments on my e-commerce site. Instead, I would like the courier to handle package delivery and collection of fees. How can I modify the PayPal script to bypass validations and only register payments upon arrival? ...

Showing formatted JSON (Large Object) on an HTML page

Having trouble displaying formatted JSON in an HTML page, especially when dealing with larger objects (an array of objects). The current method involves using JSON.stringify(data) to display the JSON object upon receiving a response from the server. The P ...

Retrieve the output of a function in TypeScript

I'm encountering a challenge with returning a string instead of a function in an object value. Currently, an arrow function is returning an array of objects, and one of them needs to conditionally change a value based on the input value. Here is the ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Utilizing hooks in node.js functions

Is there a way to apply before and after hooks on a function? I need these hooks to trigger whenever the function is called. While Express.js middleware concept works for routes, I require similar hooks for functions on the server side. function main(){ ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" ev ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

Is there a JavaScript function available to remove comments from previously commented HTML code?

<div id="div1">bar</div> JQuery function addComment(element){ element.wrap(function() { return '<!--' + this.outerHTML + '"-->'; }); } addComment($('#div1')); Looking for assistance in unc ...

Update the text label to contain an input checkbox element within

I encountered this snippet of HTML in my form: <label class="ideal-radiocheck-label" onclick=""> <input id="pagamento_8" class="_input " type="checkbox" onclick="half(this,value);" checked="" value="980" name="pagamento[]" style="position: ab ...

Exploring various websites simultaneously using window.open

As a newcomer to javascript, I have encountered an issue with the window.open() method that I would like some help with. In my code, I take a user string, modify it in different ways, and then search for these variations. The intention is to open a new wi ...