0
var directorInfo = {
  "id": "1312",
  "firstName": "Wes",
  "lastName": "Anderson",
  "movies": [
    {
      "id": 70111470,
      "title": "The Royal Tenenbaums",
      "releaseYear": 2001,
      "length": "110min",
      "recentRatings": [8, 4, 6, 3, 5]
    },
    {
      "id": 654356453,
      "title": "The Life Aquatic with Steve Zissou",
      "releaseYear": 2004,
      "length": "119min",
      "recentRatings": [9, 9, 9, 10, 6]
    },
    {
      "id": 65432445,
      "title": "Fantastic Mr. Fox",
      "releaseYear": 2009,
      "length": "87min",
      "recentRatings": [9, 10, 8, 7, 7]
    },
    {
      "id": 68145375,
      "title": "Rushmore",
      "releaseYear": 1998,
      "length": "93min",
      "recentRatings": [10, 9, 10, 10, 10]
    },
    {
      "id": 75162632,
      "title": "Bottle Rocket",
      "releaseYear": 1996,
      "length": "91min",
      "recentRatings": [6, 9, 5, 8, 8]
    }
  ]
};

function findHighestRatedMovie (director) {
  var averageRatings = [];

  director.movies.forEach(movie => {
    var sum = movie.recentRatings.reduce((total, rating) => {
      return total += rating;
    }, 0);

    var average = sum / movie.recentRatings.length;

    //can't push key value of movie.title; results in unexpected token of '.'
    averageRatings.push({movie.title: average});
  })
}

Hello! I have what is a simple question but I can't figure it out why it doesn't work + a work around for this problem. So I am iterating over the movies property value which is an array. I am then reducing recentRatings property to get an average value. I am then trying to push the average value as well as it's corresponding title. However, when I try to define the property name which would be the title I get an unexpected token error of . which is when I define the object as {movie.title: average}. Now my question is why can't I define the object this way and push it into my averageRatings array? And how would I approach in a different way that would work?

1 Answers1

4

You are using incorrect JS syntax here {movie.title: average}.

If you want to have movie.title as a key of object do this:

{
   [movie.title]: average
}

Detailed explanation you can look here https://javascript.info/object#computed-properties

Mark Partola
  • 654
  • 3
  • 10
  • Thanks this works. I'm confused. Why do I need to use brackets over the key of the object? For example, if I made a new object `var newObject = {'someKey': 'someVal'};` I've just never had to use brackets for a declaration of a key in a new object. – NewAtLearningThis May 07 '20 at 23:32
  • It's just syntax. If you want to use something as a key, variable or runtime computed value `computed properties` is for this – Mark Partola May 07 '20 at 23:34
  • Got it. No wonder I had no clue, I've never even heard of `computed properties`. Thanks again! – NewAtLearningThis May 07 '20 at 23:35