Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - Why .forEach is returning undefined once called in my controller in express.js?

I have an array movies that holds objects and each object has a property called avgRating with a float or integer number. Example:

const movies = [
  {
    name: 'Rambo I', avgRating: 4.6659
  },
  {
    name: 'Rambo II', avgRating: 3.158
  },
  {
    name: 'Rambo III', avgRating: 3.956
  }
];

Inside the util.js file I have a function to round the avgRatings of each movie inside the closest 0.5 or integer:

exports.roundingAvgRating =  (movies) => {
  const moviesCopy = [...movies];
  return moviesCopy.forEach((movie) => {
    if (movie.avgRating === null) {
      movie.avgRating = null
    } else {
      movie.avgRating = Math.round(movie.avgRating * 2) / 2;
    }
  });
};

The problem is that when I call the function in my controller, it returns undefined.

const { roundingAvgRating } = require('../utils/roundingAvgRatings.js');
const roundedRatings = roundingAvgRating(searchItems)
console.log(roundedRatings) // undefined...why?
question from:https://stackoverflow.com/questions/65641196/why-foreach-is-returning-undefined-once-called-in-my-controller-in-express-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to map your movies, and you should return movie each time in loop. like this:

const movies = [
  {
    name: 'Rambo I', avgRating: 4.6659
  },
  {
    name: 'Rambo II', avgRating: 3.158
  },
  {
    name: 'Rambo III', avgRating: 3.956
  }
];

const roundingAvgRating = (movies) => {
  

  return movies.map((movie) => {
    if (movie.avgRating) {
       movie.avgRating = Math.round(movie.avgRating * 2) / 2;
    }
    return movie
  });
}

also you don't need to make copy in map


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...