我正在使用 React 和 moment.js 构建新闻提要。使用 .map
我正在渲染带有标题和内容的项目。我想检查一个项目是否与另一个项目在同一年和同一月发布。如果是这种情况,我想隐藏第二个项目的标题。
目前我的代码呈现这个:
2018 年 3 月
新闻一
2018 年 3 月
新闻二
2017 年 9 月
新闻三
2017 年 6 月
新闻四
Since item one and two share the same month and year I would like to render like this instead:
2018 年 3 月
新闻一
新闻二
2017 年 9 月
新闻三
2017 年 6 月
新闻四
Based on this answer我试图找到具有重复类名的节点,但我不完全在那里:
let monthNodes = [...document.querySelectorAll('.months')];
let months = []
monthNodes.map(month => {
months.push(month.className)
})
const count = names =>
names.reduce((a, b) =>
Object.assign(a, {[b]: (a[b] || 0) + 1}), {})
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(months)) // {March_2018: 2, December_2017: 1, November_2017: 1}
console.log(duplicates(count(months))) // [ 'March_2018' ]
也许我以错误的方式解决这个问题,首先使用 .map
是个坏主意?
更新
感谢所有出色的答案,很难在它们之间做出选择,因为它们都运行良好。我必须接受 David Ibl 的回答,因为他是第一个提供工作示例的人。
最佳答案
Array.prototype.reduce()
可用于按年
和月
以对象
形式组织您的文章
。
请参阅下面的实际示例。
// News
class News extends React.Component {
// State.
state = {
news: [
{content: 'news item one -- march 2018', date: '2018-03-02'},
{content: 'news item two -- march 2018', date: '2018-03-17'},
{content: 'news item two -- sep 2017', date: '2017-09-21'},
{content: 'news item one -- june 2017', date: '2017-06-15'}
]
}
// Render.
render = () => (
<div>
{
Object.entries(this.organised()).map(([yearmonth, articles], i) => (
<div key={i}>
<h3>{yearmonth}</h3>
{articles.map((article, j) => (
<div key={j}>
{article.content}
</div>
))}
</div>
))
}
</div>
)
// Organised.
organised = () => this.state.news.reduce((total, article) => {
const key = moment(article.date).format('YYYY MMMM')
return {
...total,
[key]: total[key] && total[key].concat(article) || [article]
}
}, {})
}
// Mount.
ReactDOM.render(<News/>,document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
关于javascript - 检查映射数组中的项目是否共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272454/