Siddhu
Siddhu

Reputation: 1

How to simplfy this loop

My doubt was i am able to insert array in loop succesfully but i need to simplyfy that code, so can any one suggest me to do that?

static async createProductReviewFromRequestBody(request_body) {
    let reviews_ratings = []
    for(let i in request_body.reviews_ratings)
    {
        let dict = {}
        dict['user_id'] = request_body.reviews_ratings[i].user_id,
        dict['user_full_name'] = request_body.reviews_ratings[i].user_full_name,
        dict['reviews_ratings_user_rating'] = request_body.reviews_ratings[i].reviews_ratings_user_rating,
        dict['reviews_ratings_description'] = request_body.reviews_ratings[i].reviews_ratings_description,
        dict['reviews_ratings_review_date'] = new Date(),
        dict['reviews_ratings_last_modified'] = new Date()
        reviews_ratings.push(dict)
    }
    return {
        product_id: request_body.product_id,
        reviews_ratings: reviews_ratings
    };
}

Upvotes: 0

Views: 31

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

Use .map to create a new array from every item in the old array. Save the Date at the beginning of the function, so you don't have to call new Date() every time, and iterate over an array of property names to keep things DRY:

static async createProductReviewFromRequestBody(request_body) {
  const now = new Date();
  const reviews_ratings = request_body.reviews_ratings
    .map((ratingsObj) => {
      const newObj = {
        reviews_ratings_review_date: now,
        reviews_ratings_last_modified: now
      };
      for (const prop of ['user_id', 'user_full_name', 'reviews_ratings_user_rating', 'reviews_ratings_description']) {
        newObj[prop] = ratingsObj[prop];
      }
      return newObj;
    });
  return {
    product_id: request_body.product_id,
    reviews_ratings // <-- can use property shorthand notation here
  };
}

Remember not to use for..in to iterate over arrays!

Upvotes: 2

Related Questions