2017-10-03 8 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