Item unchanged

Seeking help to understand object mutation during a for loop.

I anticipate that console.log(dish) will display the dish object with an updated ingredients property containing an array of shifted ingredients.

However, when I check dish.ingredients, it only displays the ingredients.

Surprisingly, logging dish shows the dish objects without the ingredients.

What could be causing this behavior?

for (let dish of dishArray) {
  dish['ingredients'] = []
  for (let ingredient of ingredientsArray) {
    if (dish._id.equals(ingredient._dishID)) {
      dish['ingredients'].unshift(ingredient)
    }
  }
  console.log(dish['ingredients'])             <------------- 
  console.log(dish)                            <-------------         
}

dishArray contains an array of dish objects fetched from a mongoose query.

Answer №1

To achieve the desired outcome, in JavaScript you can use the `==` operator without requiring any additional information about your code.

let dishArray = [{
  _id: '0'
}, {
  _id: '1'
}];
let ingredientsArray = [{
  _id: '0',
  _dishID: '0'
}, {
  _id: '1',
  _dishID: '1'
}];

for (let dish of dishArray) {
  dish['ingredients'] = [];

  for (let ingredient of ingredientsArray) {
    if (dish._id == ingredient._dishID) {
      dish['ingredients'].unshift(ingredient);
    }
  }

  console.log(dish['ingredients']);
  console.log(dish);
}

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

Extract the URL of the background image from a preexisting <div> element, or append a new attribute to the background-image property

I am facing a challenge in updating the existing background-image with a linear gradient. Currently, my CMS is generating a background-image, but I am unable to adjust the opacity using a linear gradient. My goal is to darken the background-image using CSS ...

How can I set a default value for a v-select using a function in vue.js / vuetify?

I'm new to utilizing vuetify and I am curious if there is a method to set a value for a v-select using a function. My form can create an enterprise, leveraging apollo.js to connect with the database. Although all fields populate correctly when modifyi ...

moving passport objects between different routes

Feeling a bit lost in setting up my node application with Express and Passport for authentication. Came across a helpful guide by scott.io that got me started here Everything works fine, but I want to organize my routes better. Planning to have separate r ...

Is there a way to sequentially load two iframes, with the second one loading only after the first one is fully loaded

Having two different links that trigger ajax calls can be tricky if only one request is allowed per load. This may result in both iframes displaying the same data. Is there a way to work around this issue? Perhaps loading one iframe first and then triggeri ...

Error: SyntaxError - Invalid JSON character encoding detected

When handling POST requests with ajax in my controller, I also add data from GET requests directly to the js-code. The code snippet below is from mycontroller.php: $sServiceNumber = isset($_POST['ServiceNumber']) ? $_POST['ServiceNumber&ap ...

Attempting to load the parent window of a framed page from a separate domain results in a permission denial issue in Internet

Having an issue with a login page that is hosted within an iframe on a different domain. After a successful login, I am attempting to load the following page: <html> <head> </head> <body onload="parent.window.loca ...

Tips for processing bound data in AngularJS

Is it possible to manipulate data that is bound with AngularJS after the fact? I am creating a basic search page and have generated the results using this code: ... <div class="row" ng-repeat="document in sc.searchResult.content"> <blockquot ...

Include draggable functionality to a seating chart that is generated dynamically

I developed a function that generates table seats dynamically with equal spacing. The issue arises when I try to drag names from a list and drop them onto the seats as children. Unfortunately, I can't seem to achieve this functionality with the dynami ...

Struggling to make the switch operational

I'm struggling to make this switch statement work. I want to have multiple conditions like in an if-else statement, but I can't seem to figure out how to add more than two conditions. function spriteAI1() { var posX = c2Sprite.p ...

Save user sessions in a database using node.js, express, and mongoose-auth

I have a question about authentication and sessions in node.js. So, I've set up authentication using express.js and mongoose-auth with mongodb: app.use(express.cookieParser()); app.use(express.session({ secret: 'esoognom'})); app.use(auth. ...

Display the DIV specifically for visitors arriving from Facebook

I want to display a specific DIV on the product page only if the user has visited from Facebook. Currently, I am using the following code to check if they arrived from Facebook: var ref = document.referrer; if (ref.match(/^https?:\/\/([^\ ...

Sequelize: When attempting to use .get({plain: true})) method, an error is returned indicating that .get is

I'm facing a strange issue as I am able to retrieve only the values of an instance in other parts of my code without any problems. Can you spot what might be wrong with my current code? app.get('/profile', checkAuth, function(req, res) { ...

What steps are involved in managing and retrieving data within session storage?

Here's an illustration of the data I receive after a successful ajax call response. The obj.DATA appears like this: { "A43D": { "FIRSTNAME": "Mike", "EMAIL": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b161 ...

Tips for displaying a restricted quantity of items in a list according to the number of li lines used

My approach involves using a bulleted list to display a limited number of items without a scrollbar in 'UL' upon page load. On clicking a 'more' button, I aim to reveal the remaining items with a scrollbar in UL. The following code acco ...

Using whitespace to format a document.write in JavaScript

I'm in the process of creating a dynamic table using JavaScript and a set of objects. I've managed to structure it, but now I require some extra white space between them, almost like tabbing them out. How can I achieve this efficiently with my cu ...

Managing JavaScript events in the console

Running a server for a video game in node.js where the console communicates with clients via websockets. I have a function to spawn enemies from a MySQL database, but I am encountering an error that seems to be related to a jQuery script... I want the scr ...

Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method. Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080 Here is an image of the console showing ...

Modifying the Carousel Interval on the Fly: A Guide

I've been trying to figure out how to adjust the interval time on a Bootstrap carousel. I know you can set it initially using: $('.carousel').carousel({interval: 1000 }); But what if I want the interval to change to 2 seconds after, let&ap ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

"Adding content to the DOM using AJAX, the data is showing up as plain text rather than formatted

As part of my project, I am working on incorporating data retrieved through an AJAX request into the DOM to be able to manipulate it further. However, I encountered an issue where the data displayed as a string instead of HTML when appended to the DOM. Bel ...