如何在Angular2的嵌套对象中动态设置键的值

时间:2019-01-24 11:21:37

标签: angular typescript

我正在为发布设置JSON对象,我需要动态设置键的嵌套对象值。如何使用Angular2 / Typescript。

我尝试从json中获取值并通过重复性函数调用对其进行动态设置。可能递归可以解决问题,有人可以帮我如何为该函数编写递归。

let encounterPayLoad = {  
      patient:this.orderEncounter.patient.uuid,
      visit:this.orderEncounter.visit.uuid,
      encounterType:this.orderEncounter.encounterType.uuid,
      obs:[  
         {  
            groupMembers:[  
               {  
                  concept:val,//setting concept values as dynamically
                  value:"1000"
               },
         }
      ],
      orders:[  
      ],
      encounterProviders:[  
         {  
          provider: this.appConstants.defaultProviderUUID,
          encounterRole: this.appConstants.defaultEncounterRoleUUID
         }
      ]
   }
   this.groupMember.push(encounterPayLoad);
   console.log("@payLoad",this.groupMember);
  }

我希望最终对象的形状如下所示。目前,它在groupMembers内部仅处于一个级别。

{  
   "patient":"e56faafe-70e2-422d-a260-a1c69e72a54c",
   "visit":"7848a99a-323b-4873-9711-2b5f27be86f9",
   "encounterType":"7c179057-ae3d-44d8-b9e7-f5e514992f41",
   "obs":[  
      {  
         "groupMembers":[  
            {  
               "concept":"4876e25c-f580-4a84-9357-a283de220b44",
               "value":"1000"
            },
            {  
               "concept":"964f1f1e-7c26-4e59-bb23-692a4ae02c6f",
               "value":"2000"
            },
            {  
               "concept":"02f962f7-c864-474e-a63a-56feed2ad2dc",
               "value":"3000"
            }
         ],
         "concept":"745449b2-c0e6-4f23-8428-942499142533",
         "order":"0472a6fe-63c5-40f9-b761-dbfa6f91e117"
      }
   ],
   "orders":[  

   ],
   "encounterProviders":[  
      {  
         "provider":"f9badd80-ab76-11e2-9e96-0800200c9a66",
         "encounterRole":"240b26f9-dd88-4172-823d-4a8bfeb7841f"
      }
   ]
}

1 个答案:

答案 0 :(得分:0)

要生成的字符串称为UUID。您可以在线找到函数以使用JavaScript为您生成它。

这是一个类似的功能,由JavaScript: Function to create a UUID identifier提供:

private create_UUID() {
  var dt = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (dt + Math.random() * 16) % 16 | 0;
    dt = Math.floor(dt / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

然后您可以像这样在代码中调用它:

let encounterPayLoad = {
  patient: this.orderEncounter.patient.uuid,
  visit: this.orderEncounter.visit.uuid,
  encounterType: this.orderEncounter.encounterType.uuid,
  obs: [{
      groupMembers: [{
          concept: this.create_UUID(),
          value: "1000"
        },
      }
    ],
    orders: [],
    encounterProviders: [{
      provider: this.appConstants.defaultProviderUUID,
      encounterRole: this.appConstants.defaultEncounterRoleUUID
    }]
  }
  this.groupMember.push(encounterPayLoad);
  console.log("@payLoad", this.groupMember);
}