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', 'article 2'],
sports: ['article 2']
}
解决方案
您可以使用Object.entries、reduce和forEach轻松实现此结果。
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);
推荐阅读
- metaprogramming - 如何获取 MAXScript 函数的参数列表
- sql-server - 获取 SQL Server 中所有系统数据库的列表
- .net - 我们应该如何使用 NuGet 打包通用 Windows 类库?
- python - 刚刚在 Windows 10 上安装 Juypter 无法启动
- javascript - Laravel 和 Vue.js 使用 fetch 的 put 方法
- ios - 如何调用api url方法,以便应用程序每次从后台进入前台时重新加载?
- go - 为什么接受自定义结构来代替错误?
- aws-lambda - 为 API CRUD 定义 Lambda 函数的最佳方法是什么?
- python - 在同一行 Python 中多次输入变量 x
- python - 计算掩码numpy数组的给定轴的模式