早上好,在array.map之后,我有一個數(shù)組,其中包含相同的賦值和一些嵌套的評級:
const assignments = [
{
name: "assignmentOne",
difficultyRating: 1,
funRating: 2
},
{
name: "assignmentOne",
difficultyRating: 3,
funRating: 4
},
{
name: "assignmentOne",
difficultyRating: 5,
funRating: 1
}
]
現(xiàn)在我想得到總難度/樂趣評分,如下所示:
//Both the difficulty and fun rating in the same record
const assignmentsTotal = [
{
name: "assignmentOne",
totalDifficultyRating: 9,
totalFunRating: 7
}
]
//Difficulty and fun rating as separate records
const assignmentsDifficultyTotal = [
{
name: "assignmentOne",
totalDifficultyRating: 9
}
]
const assignmentsFunTotal = [
{
name: "assignmentOne",
totalFunRating: 7
}
]
我很有信心最好的方法就是使用reduce方法。經(jīng)過一番挖掘之后,唯一接近我想要實現(xiàn)的是下面的文章,但是我不能讓它正常工作。有沒有一個好的方法從上面的起點開始,或者在使用reduce方法之后使用array.map創(chuàng)建單獨的數(shù)組會更好嗎?
如果要在數(shù)組中查找相同的“name”對象,下面應(yīng)該可以:
如果要按名稱對對象進(jìn)行分組,請查看lodash groupby函數(shù)。一般來說,lodash在所有array/obj功能中都非常方便。