首页 > 解决方案 > 如何在 for 循环中将 Object 属性推送到数组中?

问题描述

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});
  })
}

你好!我有一个简单的问题,但我无法弄清楚为什么它不起作用+解决这个问题的方法。所以我在遍历数组的 movies 属性值。然后我减少recentRatings财产以获得平均值。然后我试图推动平均值以及它对应的title. 但是,当我尝试定义属性名称时,title我得到一个意外的令牌错误,.当我将对象定义为{movie.title: average}. 现在我的问题是为什么我不能以这种方式定义对象并将其推送到我的 averageRatings 数组中?我将如何以不同的方式进行处理?

标签: javascriptobject

解决方案


您在这里使用了不正确的 JS 语法{movie.title: average}

如果您想将movie.title对象作为键,请执行以下操作:

{
   [movie.title]: average
}

详细解释你可以看这里 https://javascript.info/object#computed-properties


推荐阅读