如何循环包含Javascript中的对象的对象

我有一个看起来像这样的对象(我们称其为帖子)


[ { _id: 5cc2d552939a9b290bfaee18,

    rating: 1,

    __v: 0 },

  { _id: 5cc2d6362c9b3729253d14eb,

    rating: 4,

    __v: 0 } ]

该对象的大小改变。


每次调用该函数时,我都希望遍历帖子,并求和。然后,我想将等级除以帖子中的项目数。


我试图做这样的事情


Object.keys(posts).forEach(function (item, value) {


        });

但是无法获取实际数据


桃花长相依
浏览 146回答 3
3回答

慕婉清6462132

我有一个对象(我们称它为post)。我们称其为array或map。而且,您始终可以遍历数组。您可以for为此使用简单循环。循环将使您获得数组元素一个接一个的元素,在您的情况下这将是对象。现在,您可以轻松获取rating每个对象的属性值并将它们加起来,然后除以数组的长度。你应该以类似var data = [ { _id: '5cc2d552939a9b290bfaee18',&nbsp; &nbsp; &nbsp; &nbsp; rating: 1,&nbsp; &nbsp; &nbsp; &nbsp; __v: 0 },&nbsp; &nbsp; &nbsp; { _id: '5cc2d6362c9b3729253d14eb',&nbsp; &nbsp; &nbsp; &nbsp; rating: 4,&nbsp; &nbsp; &nbsp; &nbsp; __v: 0 } ];&nbsp; &nbsp; var sum = 0;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for(var i=0; i< data.length; i++){&nbsp; &nbsp; &nbsp; sum = sum + data[i].rating;&nbsp; &nbsp; }&nbsp; &nbsp; var result = sum/data.length;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; console.log(result);我已经解释了这一切,所以您不仅可以复制并粘贴它。请务必阅读说明。

凤凰求蛊

你有一个数组,而不是一个对象。您需要遍历数组,而不是对象&nbsp;let posts = [&nbsp;{ _id: 5cc2d552939a9b290bfaee18,rating: 1, __v: 0 },{ _id: 5cc2d6362c9b3729253d14eb,rating: 4,__v: 0 }&nbsp;], sum = 0, average = 0;//so you need the average of the ratings, get the sum of the ratingsposts.map(post => sum += post.rating);//divide the sum by the length of the itemsaverage = sum/posts.length

慕妹3146593

哦,对于初学者来说,您遍历仅键的数组就Object.keys可以得到键,而不是值,这样就没用了。&nbsp; &nbsp; function getAverageRating(posts, detailed)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; let totalPosts = 0;&nbsp; &nbsp; &nbsp; &nbsp; let totalRatings = 0;&nbsp; &nbsp; &nbsp; &nbsp; posts.forEach(function (item, index) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; totalRatings += item.rating;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; totalPosts++;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; if(detailed){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return {"total_posts":totalPosts, "sum_ratings":totaltotalRatings, "avg":totaltotalRatings/totalPosts}&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return totaltotalRatings/totalPosts&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript