我正在寻找一种有效的方法来返回数组内对象中的唯一值。例如下一个对象:
{
"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"]
}
}]
}
Run Code Online (Sandbox Code Playgroud)
我想返回的是以下内容:
{"option": [ "A", "B", "C" ] },{"type": ["A", "B", "C"] }
Run Code Online (Sandbox Code Playgroud)
所以我想为标签对象内的每个项目一个新对象。之后,我想要一个包含所有产品的所有唯一值的数组。
我对另一个函数做了一些同样的事情:
Array.from(new Set(data.map(p => { return p.category; })))
Run Code Online (Sandbox Code Playgroud)
这是一个更高的级别,使其更容易。有人可以将我推向正确的方向吗?
改为制作两组,一组用于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]
});Run Code Online (Sandbox Code Playgroud)
对于任意键,另一种选择:
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);Run Code Online (Sandbox Code Playgroud)