来自http调用的响应是一个公司对象数组,如下所示:

response = [{
    "name": "CompanyName1",
    "registrations": [
      {
        "country": "en",
        "register": "registerType1",
        "amount": 2
      },
      {
        "country": "wa",
        "register": "registerType2",
        "amount": 1
      },{
        "country": "en",
        "register": "registerType1",
        "amount": 3
      },
       {
        "country": "sc",
        "register": "registerType3",
        "amount": 2
      },
      {
        "country": "wa",
        "register": "registerType3",
        "amount": 2
      }
    ]
  },
  {
    "name": "CompanyName2",
    "registrations": [
      {
        "country": "wa",
        "register": "registerType1",
        "amount": 3
      },
      {
        "country": "sc",
        "register": "registerType3",
        "amount": 1
      }
    ]]

如果registerType1;registerType2,我需要将公司的注册按注册名和国家分组/sum到一个新的propertyName(registerType12)中,否则只保留property name registerTypen。对于公司名称1,我需要得到这样的结果:
CompanyName1: [{country:en, registerType_12, amount:5},
              {country:wa, registerTyoe_12, amount:1,
              {country:sc, registerType3, amount:4}
              }]

最佳答案

这不需要typescript或rxjs。它可以用纯JavaScript实现。
jsbin链接:https://jsbin.com/yujocofesu/edit?js,console

response.reduce((finalObj, obj)=>{
     finalObj[obj.name] =
         obj.registrations
             .map(reg => Object.assign(reg,
                  {register: (
                     reg.register ==='registerType1'||
                     reg.register==='registerType2') ?
                     'registerType_12': reg.register
                   })
              )
              .reduce(mergeSimilar, []);
     return finalObj;
   },{});


function mergeSimilar(newList, item){
  let idx = newList.findIndex(
      i=> i.country === item.country && i.register === item.register);
  if(idx>-1){
    newList[idx].amount += item.amount;
  }else{
    newList.push(item)
  }
  return newList;
}

这给出了响应
{
  CompanyName1: [{
    amount: 5,
    country: "en",
    register: "registerType_12"
  }, {
    amount: 1,
    country: "wa",
    register: "registerType_12"
  }, {
    amount: 2,
    country: "sc",
    register: "registerType3"
  }, {
    amount: 2,
    country: "wa",
    register: "registerType3"
  }],
  CompanyName2: [{
    amount: 3,
    country: "wa",
    register: "registerType_12"
  }, {
    amount: 1,
    country: "sc",
    register: "registerType3"
  }]
}

08-18 11:29