首页 > 解决方案 > 通过键javascript过滤数组属性对象的对象

问题描述

我有这个对象,我想按新闻、搞笑和体育过滤文章

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']
}

标签: javascript

解决方案


您可以使用Object.entriesreduceforEach轻松实现此结果。

const articles = {
  article_1: {
    tags: ["news", "funny"],
  },
  article_2: {
    tags: ["sports", "funny"],
  },
};

function groupArticlesByTag(obj) {
  return Object.entries(obj).reduce((acc, [key, val]) => {

    val.tags.forEach((tag) => {
      if (acc[tag]) {
        acc[tag].push(key);
      } else {
        acc[tag] = [key];
      }
    });

    return acc;
  }, {});
}

const articlesByTag = groupArticlesByTag(articles);
console.log(articlesByTag);

您甚至可以使用逻辑空值赋值 (??=)使其更短一些

const articles = {
  article_1: {
    tags: ["news", "funny"],
  },
  article_2: {
    tags: ["sports", "funny"],
  },
};

function groupArticlesByTag(obj) {
  return Object.entries(obj).reduce((acc, [key, val]) => {

    val.tags.forEach((tag) => {
      (acc[tag] ??= []).push(key);
    });

    return acc;
  }, {});
}

const articlesByTag = groupArticlesByTag(articles);
console.log(articlesByTag);


推荐阅读