javascript - 如何在对象数组中只包含一次值?
问题描述
我有这个对象数组。
[
{
tier1: "Normal",
tier2: "none",
tier3: "none",
tier4: "none",
tier5: "none",
},
{
tier1: "Urgent",
tier2: "GCC & Labour",
tier3: "new",
tier4: "Cancellation",
tier5: "Cancellation",
},
{
tier1: "Urgent",
tier2: "Foreigner",
tier3: "renew",
tier4: "Cancellation",
tier5: "none",
},
]
我只需要一次获取tier1
,tier2
和values 。tier3
tier4
tier5
所以假设在上面的例子tier1
中有Normal
一次和Urgent
两次,所以它将在下一个元素中被删除。tier5
hasnone
在第一个元素中,因此将从最后一个元素中删除,因为它已经存在。
输出将是
[
{
tier1: "Normal",
tier2: "none",
tier3: "none",
tier4: "none",
tier5: "none",
},
{
tier1: "Urgent",
tier2: "GCC & Labour",
tier3: "new",
tier4: "Cancellation",
tier5: "Cancellation",
},
{ tier2: "Foreigner", tier3: "renew" },
]
解决方案
维护Set
对象中每个键的值。使用map
并获取更新后的过滤对象。(更新的对象将是尚未拥有的键)
const all = {};
const updateObject = (obj) =>
Object.fromEntries(
Object.entries(obj).filter(([key, value]) => {
if (!(key in all)) {
all[key] = new Set();
}
const result = !all[key].has(value);
all[key].add(value);
return result;
})
);
const output = arr => arr.map(updateObject);
data = [
{
tier1: "Normal",
tier2: "none",
tier3: "none",
tier4: "none",
tier5: "none",
},
{
tier1: "Urgent",
tier2: "GCC & Labour",
tier3: "new",
tier4: "Cancellation",
tier5: "Cancellation",
},
{
tier1: "Urgent",
tier2: "Foreigner",
tier3: "renew",
tier4: "Cancellation",
tier5: "none",
},
];
console.log(output(data));
推荐阅读
- user-interface - Xamarin Forms Frame 不随内容扩展
- android - 应用程序未在通知访问设置 Android 中列出
- ios - 未使用 AVAssetWrite 录制音频
- react-native - react-native 搜索栏和 flatList 问题
- javascript - 悬停图像大小问题
- cordova - 离子 2 SSl 钉扎
- autohotkey - 在 AutoHotKey 中重用 GUI 输入
- mysql - 将数据从 aws s3 导入 mysql 或任何非 aws 数据库
- c# - 我应该选择哪种 C# 项目类型?需要 UWP 设计功能,但需要 WPF 功能
- c++ - 用户输入大数字时的无限循环