使用RXJS将特定对象属性将平面对象列表分组到嵌套列表中

时间:2017-10-03 17:17:40

标签: typescript 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"
  },
]

我希望使用Observable和RxJs一起按字典分组这样的词典:

NestedObjects

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

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

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

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

    }]
}]

当我尝试我认为更接近的运算符是reduce或者只是使用do而我正在考虑做这样的代码,我对集合对象有副作用。

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());

是否有另一个操作员使这个投影清晰,没有副作用?

1 个答案:

答案 0 :(得分: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;
  });