所以,我有一些组件:
曲目:
render() {
const tracks = [
{id: '1', artistName: "Eagles", trackName: "Hotel California"},
{id: '2', artistName: "Halsey", trackName: "Without Me"},
{id: '3', artistName: "Ariana Grande", trackName: "thank u, next"}
]
return (
<div>
{tracks && tracks.map(track => {
return (
<TrackSummary track={track} key={track.id} />
)
})}
</div>
)
}
TrackSummary:
const TrackSummary = ({track}) => {
return (
<div>
<div className="card">
<h5 className="card-header">
<strong>{track.trackName}</strong> by: {' '} {track.artistName}
</h5>
</div>
</div>
)
}
我想做的是,如果重复{track.trackName}
,我不想将它们显示两次,而只显示一次,其旁边是重复次数。
例如此处:
我两次展示Without Me by: Halsey
。相反,我想在显示编号2
旁边显示一次,因为音轨出现了两次。
谢谢您的帮助!
答案 0 :(得分:1)
首先,我们需要使用trackName
按数组分组,然后计算有多少重复项,并将其添加到count
var arr = [
{id: '1', artistName: "Eagles", trackName: "Hotel California"},
{id: '2', artistName: "Halsey", trackName: "Without Me"},
{id: '3', artistName: "Ariana Grande", trackName: "thank u, next"},
{id: '2', artistName: "Halsey", trackName: "Without Me"}
]
var grouped = _.groupBy(arr,'trackName');
var mappedArr = [];
_.map(grouped,function(val,key){
mappedArr.push({
count: val.length,
...val[0]
})
});
console.log(mappedArr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
希望有帮助。 干杯!