javascript - 遍历列表中的对象并返回唯一值
问题描述
我正在寻找一种有效的方法来返回数组内对象中的唯一值。例如下一个对象:
{
"products": [{
"id": 1,
"category": "test1",
"tags": {
"option": ["A", "B"]
}
}, {
"id": 2,
"category": "test2",
"tags": {
"option": ["B"],
"type": ["A", "B", "C"]
}
}, {
"id": 3,
"category": "test1",
"tags": {
"type": ["A"]
}
}, {
"id": 4,
"category": "test2",
"tags": {
"option": ["B", "C"],
"type": ["A", "C"]
}
}]
}
我要返回的是以下内容:
{"option": [ "A", "B", "C" ] },{"type": ["A", "B", "C"] }
所以我想为标签对象内的每个项目创建一个新对象。之后,我想要一个包含所有产品的所有唯一值的数组。
我对另一个功能做了一些相同的事情:
Array.from(new Set(data.map(p => { return p.category; })))
这是一个更高的级别,这使得它更容易。有人可以将我推向正确的方向吗?
解决方案
改为制作两组,一组用于目前option
找到的 s,一组用于目前找到的type
s:
const obj = {
"products": [{
"id": 1,
"tags": {
"option": ["A", "B"]
}
}, {
"id": 2,
"tags": {
"option": ["B"],
"type": ["A", "B", "C"]
}
}, {
"id": 3,
"tags": {
"type": ["A"]
}
}, {
"id": 4,
"tags": {
"option": ["B", "C"],
"type": ["A", "C"]
}
}]
};
const options = new Set();
const types = new Set();
for (const { tags: { option=[], type=[] } } of obj.products) {
for (const o of option) options.add(o);
for (const t of type) types.add(t);
}
console.log({
option: [...options],
type: [...types]
});
对于任意键,另一种选择:
const obj = {
"products": [{
"id": 1,
"tags": {
"option": ["A", "B"]
}
}, {
"id": 2,
"tags": {
"option": ["B"],
"type": ["A", "B", "C"]
}
}, {
"id": 3,
"tags": {
"type": ["A"]
}
}, {
"id": 4,
"tags": {
"option": ["B", "C"],
"type": ["A", "C"]
}
}]
};
const setObj = {};
for (const { tags } of obj.products) {
for (const [key, arr] of Object.entries(tags)) {
if (!setObj[key]) setObj[key] = new Set();
for (const item of arr) setObj[key].add(item);
}
}
const output = Object.fromEntries(
Object.entries(setObj).map(([key, set]) => [key, [...set]])
);
console.log(output);
推荐阅读
- swift - 在可可应用程序中运行终端命令
- mysql - MySQL:仅选择最接近日期的行具有列值
- java - 滚动视图不工作。我应该怎么办?
- python - 我根据属性在 Beautiful soup 中使用 find_all 创建了一个列表。我如何返回我想要的节点?
- ios - 在 UITextView 中拆分段落并保存范围
- python - Paramiko exec_command stdout、stderr、stdin 到日志记录器
- python - 所有错误都会导致 URLconf 循环导入
- html - 在网站的日期字段中输入日期,然后单击查看报告按钮
- vb.net - 检查是否运行进程字符串 VB.Net
- google-cloud-platform - Cloud Spanner - WHERE 子句中包含大量项目的读取性能