javascript在单次迭代中为对象映射中的每个属性创建一个集合



这是怎么回事。我有4个对象。objA,objB,objC,objD。

objD,有多个属性,在它们之间有objA、objB和objC。

class objD{
constructor(objA, objB, objC, otherAttributes...){
this.objA = objA;
this.objB = objB;
this.objC = objC;
this.otherAttributes = otherAttributes;
...
}
}

我为每个objAs、Bs、Cs以及objD都有一个Map((。

但是,我只需要过滤objD中使用的objA、Bs和Cs。毕竟,并不是所有的objA、Bs和Cs都被使用,所以,在我的选项中显示它们没有意义。

所以,我正在努力实现:在一次迭代中从使用过的objA、objB和objC中获得3个集合。当然,我可以对ObjDs的映射进行3次迭代。但我想在一次迭代中做到这一点。

以下是我迄今为止所做的:

做一组目标,例如:

let mapOfObjDs;  //this is the map containing all the objDs.
let setOfObjAs = new Set(Array.from(mapOfObjDs.values(), (x) => x.objA))

我设法得到一个数组3 x n(n是对象的数量(:

let map = Array.from(mapOfObjDs.values()).map((x) => 
[
x.objA,
x.objB,
x.objC
]);

但我不知道如何在不迭代3次的情况下将其转换为3个集合。有可能在一次迭代中做到这一点吗?

您可以创建一个集合数组,并迭代mapOfObjDs来插入每个值。

例如:

// Map of objects
let mapOfObjDs = new Map([
["1", new objD("a1","b1","c1")],
["2", new objD("a2","b2","c2")],
["3", new objD("a3","b3","c3")],
["4", new objD("a4","b4","c4")]
]);
// Create empty array of set
let arrOfObjs = Array.from({length: 3}, (e) => new Set());
// Insert values
for (const objd of mapOfObjDs.values()) {
arrOfObjs[0].add(objd.objA);
arrOfObjs[1].add(objd.objB);
arrOfObjs[2].add(objd.objC);
}
console.log(arrOfObjs);

输出:

[
Set(4) { 'a1', 'a2', 'a3', 'a4' },
Set(4) { 'b1', 'b2', 'b3', 'b4' },
Set(4) { 'c1', 'c2', 'c3', 'c4' }
]

类似的东西?

class objD{
alldata = {
A: new Set(),
B: new Set(),
C: new Set()
}
constructor(objA, objB, objC, otherAttributes...){
this.objA = objA;
this.objB = objB;
this.objC = objC;
this.otherAttributes = otherAttributes;

alldata.A.add(objA);
alldata.B.add(objB);
alldata.C.add(objC);
}
}

然后,您可以通过objD.alldata.A等访问列表

最新更新