2017-10-03 7 views
1

を使用して、特定のオブジェクトのプロパティによって、ネストされたリストにフラットなオブジェクトリスト私はこのようなコレクションを持っている:グループRXJS

FlatObject 
[ 
    { 
    id:"1", 
    name:"test1", 
    group: "A" 
    }, 
    { 
    id:"2", 
    name:"test2", 
    group: "B" 
    }, 
{ 
    id:"3", 
    name:"test3", 
    group: "B" 
    }, 
    { 
    id:"4", 
    name:"test4", 
    group: "A" 
    }, 
] 

をそして、私はこのようなグループの何かによってグループ化されたRxJs辞書で観察を使用して取得したいです:私は近い減らすか、単に使用しないと私は私がコレクションオブジェクトへの副作用を持って、このコードのような何かを考えていたと思いオペレータを試してみました

NestedObjects 

[{ 
    "group": "A", 
    "objectProps": [{ 
     "id": "1" 
     "name": "test1", 

    }, 
    { 
     "id": "4" 
     "name": "test4", 

    }] 
}, 
{ 
    "group": "B", 
    "objectProps": [{ 
     "id": "2" 
     "name": "test2", 

    }, 
    { 
     "id": "3" 
     "name": "test4", 

    }] 
}] 

let collectionNestedOBjects: NestedObjects[]; 
..... 
.map((response: Response) => <FlaTObject[]>response.json().results) 
.reduce(rgd, rwgr => { 

       // Soudo Code 

       // Create NestedObject with group 

       // Check if collectionNestedOBjects has an object with that group name 
         Yes: Create a objectProps and add it to the objectProps collection 
         No: Create a new NestedObject in collectionNestedObjects and Create a objectProps and add it to the objectProps collection 

      } 
      ,new ReadersGroupDetail()); 

この投影法を明確にし、副作用がない別の演算子がありますか?

答えて

0

あなたは.map()演算子を使用して、必要な型にマップすることができます

const data: Observable<NestedObject[]> = getInitialObservable() 
    .map((response: Response) => <FlatObject[]>response.json().results) 
    .map((objects: FlatObject[]) => { 
    // example implementation, consider using hashes for faster lookup instead 
    const result: NestedObjects[] = []; 

    for (const obj of objects) { 
     // get all attributes except "group" into "props" variable 
     const { group, ...props } = obj; 
     let nestedObject = result.find(o => o.group === group); 
     if (!nestedObject) { 
     nestedObject = { group, objectProps: [] }; 
     result.push(nestedObject); 
     } 
     nestedObject.objectProps.push(props); 
    } 
    return result; 
    }); 
+0

はい、それは私が追加され、テストされ、それがうまくデータをグループ化し、戻り結果がありませんでした。この作品 – Devsined