Update the information for every ride to include an appropriate park_id instead of the `park_name` property

I created a function that takes an array of objects and modifies one of the object's names to its corresponding property id. Here is the function implementation:

function prepareRidesData(rides, parks) {
  if (!rides.length) return [];

  const parksLookup = {};
  parks.forEach(({ park_id, park_name }) => {
    parksLookup[park_name] = park_id;
  });

  const updatedRides = rides.map((ride) => {
    ride.park_id = parksLookup[ride.park_name];

    delete ride.park_name;
    console.log(ride);
          
    return ride;
  })
  
  return updatedRides;
}

I ran some tests using this format:

test("Return two park name with id only", () => {
  
        const input =([{
            ride_name: "Tidal Wave",
            year_opened: 2000,
            park_name: "Thorpe Park",
            votes: 1,
          },
          {
            ride_name: 'Nemesis',
    year_opened: 1994,
    park_name: 'Alton Towers',
    votes: 5,
          }]);
    
        const actual = prepareRidesData(input);
    
        expect(actual).toEqual([ {
            ride_name: "Tidal Wave",
            year_opened: 2000,
            park_id: 1,
            votes: 1,
          },
          {
            ride_name: "Nemesis",
            year_opened: 1994,
            park_id: 5,
            votes: 1,
          }]);
    
      });

I encountered an error - TypeError: Cannot read properties of undefined (reading 'forEach')

I need assistance in identifying where I made an error that is causing it not to execute correctly.

The goal is to replace the park name with its corresponding park id.

Answer №1

In the function you defined, it takes two parameters: rides and parks:

function organizeRidesData(rides, parks) {

However, when you invoke the function, you are only passing one parameter: input:

const result = organizeRidesData(input);

This results in rides acquiring the value of input while parks remains undefined, leading to an error. To fix this issue, make sure to pass both rides and parks into the function.

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

Ways to locate two div class elements that are generated dynamically

I am looking to dynamically create 2 divs in different locations. One for displaying information and another for editing information. I want to be able to delete both divs with the same class when using the delete button. Since they are located in differe ...

Having difficulty sending emails with Nodemailer

This is a simple example showcasing the usage of Nodemailer library. var http = require('http'); var port = process.env.PORT || 8080; var async = require('async'); var nodemailer = require('nodemailer'); // Creating a transp ...

Can you help me transform this javascript code into a JSON format?

Is there a way for me to organize my data so that I have one main question with 5 choices, each associated with a vote? It's like thinking of it as a tree where the question is the root and has 5 leaves, representing the choices, and each choice furth ...

Limiting input to specific characters is effective on Chrome, but unfortunately does not function on Firefox

This code snippet is designed to restrict user input to lowercase letters from a-z, numbers from 0-9, and the dash character "-". While it functions correctly in Chrome, it does not allow any input in Firefox. What could be causing this issue? $('#sl ...

The Vue v-model-bound HTML element is unable to update the Vue instance when a different JavaScript entity binds to it and modifies the data

In my project, I have implemented Vue.js for two-way data binding on a remote control alarm clock. The main code can be found here. You can access the running instance of the server here. While most of the page uses Vue and JavaScript for rendering, I de ...

How can I create a computed field in TypeORM by deriving its value from other fields within the same Entity?

My goal is to implement a 'rating' field in my User Entity. Within the User Entity, there exists a relationship with the Rating Entity, where the User has a field called ratingsReceived that eagerly loads all Ratings assigned to that User. The & ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. https://i.sstatic.net/5bHFO.png It displays "Sorted by ascending o ...

I am looking to dynamically fill my form fields with data retrieved from my database through an AJAX call to another PHP file

I am attempting to dynamically populate my form fields with data retrieved from a database row using ajax. The goal is to send the id of the row I need when a specific button is clicked. Although I have managed to successfully fetch the desired row in the ...

Where can I locate the list of events supported by CKEditor 4?

Looking for the list of available events I attempted to locate the event list in the official documentation, but unfortunately came up short. I resorted to searching through the source code using .fire("/s+") to identify all available events. However, thi ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Having trouble setting a value as a variable? It seems like the selection process is not functioning properly

My Hangman game has different topics such as cities and animals. When a user selects a topic, the outcome should be a random item from that specific topic. For example: London for cities or Zebra for animals. Currently, I am only generating a random lett ...

What is the process for attaching the stack when initializing and throwing errors separately in JavaScript?

In all the documentation I've read, it consistently advises to both throw and initialize errors on the same line. For example: throw new Error("My error"); But what if you were to first initialize the error and then throw it on separate lines? For ...

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

Trouble locating the ID selector within a nested Backbone view

Within this code snippet, I am utilizing the element controller pattern to display a collection of products. The main view template is rendering properly, showing all elements and the div selector "#cart-wrapper". However, when the main view calls the nest ...

Is there a way to upload a file using express/multer without triggering a redirect?

Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project. I have implemented a file upload feature that should provide a response indicating whe ...

Stop the npm start command with a specific error message if the file is not found in the repository

Can the npm start process be stopped or cancelled if a specific file is not found in your codebase? I am looking to end the process if the file dev-variables.js is missing, preferably displaying a custom error message like "You are missing the dev-variabl ...

Utilize Angular 8 to dynamically populate Input values with data pulled from an API

I need help with setting the input value dynamically using data from my API. Once I click send, I want it to be saved in the database. However, I am struggling to dynamically populate the input field. Can someone guide me on the right approach to achieve t ...

Unable to send a POST request to http://localhost:5000/api/createuser

During my journey through a MERN stack project tutorial on YouTube, I've come across a roadblock in the middle of my progress. The issue at hand involves the incorporation of user registration, which is a recent addition to my project. Utilizing Thund ...

What are the steps to switch to a root page after a successful sign-in with Ember-Auth?

After successfully implementing Ember-Auth using a pure token based approach, I am facing a challenge in redirecting users to the root of my app once they sign in. Although I know about actionRedirectable (refer to for details), since I am using a pure t ...

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...