javascript - 如何在 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 数组中?我将如何以不同的方式进行处理?
解决方案
您在这里使用了不正确的 JS 语法{movie.title: average}
。
如果您想将movie.title
对象作为键,请执行以下操作:
{
[movie.title]: average
}
详细解释你可以看这里 https://javascript.info/object#computed-properties
推荐阅读
- docker - 如何使用letsencrypt进入具有不同端口号的gitlab-container
- python - XML,使用 Python 在 SubElement 中添加 SubElement
- javascript - 如何在构造函数参数中使用泛型
- python-3.x - 为什么在向具有不同 dtype 的二进制图像添加噪声时会得到不同的结果
- flutter - 如何在 Flutter 中启动 WebViewController
- google-cloud-storage - 云存储 API 的 nextPageToken 是否过期?
- python - 当用户输入字典中的键或值时,仅保存一次 KEY
- java - 为什么我的字符串设置为像我的整数值一样显示为空?(爪哇)
- javascript - process.stdin.on('data'...) 不会从控制台读取
- php - 拉拉维尔。errno: 150 "外键约束格式不正确"