按键javascript筛选数组属性对象的对象
我有这个目标,我想过滤的新闻,有趣的和体育文章按键javascript筛选数组属性对象的对象,javascript,Javascript,我有这个目标,我想过滤的新闻,有趣的和体育文章 const articles = { article_1: { tags: ['news', 'funny'] }, article_2: { tags: ['sports', 'funny'] } } 我想筛选出结果 const articlesByTag = groupArticlesByTag(articles); articlesByTag = { news: ['article 1'], funny: ['article 1',
const articles = {
article_1: {
tags: ['news', 'funny']
},
article_2: {
tags: ['sports', 'funny']
}
}
我想筛选出结果
const articlesByTag = groupArticlesByTag(articles);
articlesByTag = {
news: ['article 1'],
funny: ['article 1', 'article 2'],
sports: ['article 2']
}
您可以使用和轻松实现此结果
const-articles={
第1条:{
标签:[“新闻”,“有趣”],
},
第2条:{
标签:[“运动”、“有趣”],
},
};
功能组ArticlesByTag(obj){
返回Object.entries(obj).reduce((acc,[key,val])=>{
val.tags.forEach((标记)=>{
if(附件[标签]){
acc[标签]。按(键);
}否则{
acc[tag]=[key];
}
});
返回acc;
}, {});
}
const articlesByTag=组articlesByTag(articles);
控制台日志(articlesByTag)代码>Object.keys()->提供对象的所有键的数组
.forEach()->遍历项目数组
如果键已存在,则推送到数组,否则使用键创建长度为1的数组
let groupArticlesByTag = (articles) => {
let articlesMap = {};
Object.keys(articles).map((x) => {
articles[x].tags.forEach((y)=> {
if(articlesMap[y]==undefined){
articlesMap[y] = [x]
}
else{
articlesMap[y].push(x);
}
});
});
return articlesMap;
}