Issue with adding a new value to an array within a specific key of an object

Imagine I have this function:

const createMenu = () => {
  const obj = {
    consumption: [],
  };

  return obj;
};

It's a function that, when executed, returns the object

{ consumption: [] }

My goal is to add a key inside that object which is a function. When this function is called with a string parameter, it should push the string into the array inside the 'consumption' key;

This is what I have tried:

const createMenu = () => {
  const obj = {
    consumption: [],
  };

  let order = (item) => {obj.consumption.push(item); };
  obj.order = order;

  return obj;
};

When calling this function within the object with a string parameter, like this:

createMenu().order('pizza');

and then running:

console.log(createMenu().consumption);

I expect the result to be:

['pizza']

However, it doesn't seem to be working as expected. Any help on this would be greatly appreciated.

const createMenu = () => {
  const obj = {
    consumption: [],
  };

  let order = (item) => {
    obj.consumption.push(item);
  };
  obj.order = order;

  return obj;
};

createMenu().order('pizza');

console.log(createMenu().consumption);

Answer №1

When creating two instances of createMenu, you are actually looking to create just one.

const menu = createMenu()

Furthermore, if you wish to chain the functions, you must return the object again inside the order function.

Here is an illustration:

const createMenu = () => {
  const obj = {
    items: [],
  };

  let order = (item) => {
    obj.items.push(item);
    return obj;
  };
  obj.order = order;

  return obj;
};

const menu = createMenu().order('burger');
console.log(menu.items);

Answer №2

The key to success is storing the object returned by the createMenu() function in a variable and then performing operations on that variable. The updated code snippet should do the trick.

It seems that in your current code, a new object is being created every time the createMenu() function is called, which is not the desired behavior.

const createMenu = () => {
  const obj = {
    items: [],
  };

  let addItem = (item) => {
    obj.items.push(item);
  };
  obj.addItem = addItem;

  return obj;
};

const menu = createMenu();
menu.addItem('pizza');
menu.addItem('burger');
console.log(menu.items); // ["pizza", "burger"]
.as-console-wrapper{min-height: 100% !important; top: 0}

Answer №3

If you're looking to streamline your menu creation process, perhaps consider using a JavaScript class. By initializing an array in the constructor, implementing a method to update the array with new menu items, and a final method to retrieve the desired object, you can efficiently manage your menu items.

class CreateMenu {
  
  constructor() {
    this.consumption = [];
  };

  orderItem(item) {
    this.consumption.push(item);
    return this;
  }

  getList() {
    return { consumption: this.consumption };
  }

};

const menu = new CreateMenu();

const order = menu
  .orderItem('pizza')
  .orderItem('cheese sticks')
  .getList();
  
console.log(order);

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

In JavaScript, the price can be calculated and displayed instantly when a number is entered into a form using the input type 'number'

Is there a way for me to automatically calculate the price and display it as soon as I enter a number into my form? Currently, the price is only displayed after I press submit. <script type="text/javascript"> function calculatePrice() { ...

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

"Animating a card to slide in from the left side upon clicking a button in a React app

How can we create a feature where, upon clicking "Apply Coupon" in Image 1, a window slides in from the left just above the webpage (as shown in Image 2)? Additionally, in Image 2, there is a blue transparent color on the webpage adjacent to this sliding w ...

Using the outer ng-repeat's object property to filter nested ng-repeat items

I'm currently working on nesting two ng-repeats with two separate JSON files. The goal is to filter the second ng-repeat based on parameters from the first ng-repeat. The first JSON file, $scope.matches, includes information about each match in the W ...

connection and navigation hiccup

In my current project, I am utilizing Redux and React. Within App.js, I've implemented some Routes and also make use of the connect function from react-redux. In order to avoid any potential update blocking issues, I typically wrap my component in the ...

Arrows within modal image (adjusting size based on image)

In my modal carousel, the position of the arrows changes based on the image resolution. I would like the arrows to always remain inside each image, regardless of resolution. ...

Define CSS styles based on the content of a specific cell within a table

Is there a way to target a <td> in CSS based on its content value? <table> <tr> <td>Name</td> <td>John</td> <tr> </table> For instance, how can I apply the color:bl ...

Utilizing ng-model in AngularJS to add data to an array in Mongoose and MongoDB

I am currently utilizing ng-model to input data into my MongoDB. Is there a method to utilize ng-model to insert data into an array within MongoDB? answers is an array that should include 4 strings entered by the user. I attempted adding [0], [1], [2], [3] ...

I utilize a Bootstrap modal popup to showcase user alerts across various sections of my website. Each instance of the modal window is triggered from different locations and displays personalized content

<div class="modal" tabindex="-1" role="dialog" id="myModal" data-backdrop="static" data- keyboard="false"> <div class="modal-dialog" role="document"> <div c ...

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

In Vue, the CropperJs image initially appears small, but it returns to its original size after editing

I encountered a peculiar issue while working on a website for image cropping using Vue.js and CropperJs. On the homepage, users can select an image to crop and proceed to the next page where a component named ImageCropper.vue is displayed. Strangely, the c ...

Choose items from an array using a checkbox form in PHP

I attempted to generate a form using an array, allowing the items to be selectable and collected individually as variables for processing. However, when I try to echo $_POST['citem1'], I end up with a blank screen. <?php foreach($_SESSION[&ap ...

Requesting data from a server using JavaScript/Ajax/Flash technologies over

Here is the code snippet I am currently using: swfobject.embedSWF("/Content/open-flash-chart.swf", "my_chart", "750", "300", "9.0.0", "expressInstall.swf", ...

Display HTML instead of text in print mode

Hello, I need help with printing HTML code, specifically an iframe. When I try to add my HTML iframe code, it only prints as plain text. I want to be able to see the actual iframe with its content displayed. Thank you. <script> const messages = [&apo ...

A guide on how to use Javascript to take a screenshot of an entire webpage

When a user triggers a script, it injects JavaScript code into the current page to make DOM changes. After interacting with the page, the user may want to save their modifications for later viewing or editing. However, if the original page source is edited ...

Exploring deeply nested arrays of objects until a specific condition is satisfied

My array is structured in a nested format as shown below. const tree = { "id": 1, "name": "mainOrgName", "children": [ { "id": 10, "name": "East Region", "children": [ ...

Having trouble displaying a popup dialog box in ASP.NET using JavaScript

I am trying to implement a popup dialog box in ASP.NET using JavaScript, but it's not working as expected! Below is the code I am using: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal< ...

Do we really require the hitCallback feature in Google Analytics for tracking onsite activities?

Currently, I am in the process of integrating Google Analytics into a website. Within this website, there is a page A that contains two links to page B on the same domain. My goal is to use GA to track which navigation path the user took to go from page A ...