フランク:
私は、配列内のオブジェクトに一意の値を返すために効率的な方法を探しています。たとえば、次のオブジェクト:
{
"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; })))
これは、それが容易になり、より高いレベルです。誰かが私は正しい方向にプッシュすることができますか?
CertainPerformance:
代わりに、二組を作り、のための1つのoption
sがこれまでに見つかった、とのための1つの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);