Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按键javascript筛选数组属性对象的对象_Javascript - Fatal编程技术网

按键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;
}