【问题标题】:How to add an object and array in an existing object using typescript or angular如何使用打字稿或角度在现有对象中添加对象和数组
【发布时间】:2018-04-26 00:38:01
【问题描述】:

我是 Angular 4 的初学者并使用表单生成器,在 ngSubmit 上我正在创建一个包含表单字段数据的对象。然而,在将该对象作为有效负载传递之前,我需要在表单对象中添加另一个对象和一个数组,我绞尽脑汁却无法实现它。

正如您在下面看到的,1 是我从表单生成器中获取的对象。 和2。是预期的最终对象,我需要在创建表单构建器对象后分别在对象中添加“childrenCustomerIds”和“properties”,但我不知道如何添加。

任何帮助将不胜感激..

提前谢谢..!!!

1

{ 
    "address": "string", 
    "customerId": "BGroup", 
    "email": "test@gmail.com", 
    "name": "Testing", 
    "parentCustomerId": "myCustomerId3", 
    "phoneNumber": "1111111111", 
    "primaryContactUserId": "primaryContactUserId", 
    "status": "ACTIVE", 
    "xylemPrimaryContactId": "testing" 
}

2

{
    "address": "string",
    "childrenCustomerIds": ["testing"],
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "properties": {},
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}

【问题讨论】:

  • 你能发布你的代码来构建表单吗?
  • 您需要在表单中添加这些字段,还是在提交表单后添加?有点不清楚……

标签: json angular typescript object


【解决方案1】:
var obj={ 
    "address": "string", 
    "customerId": "BGroup", 
    "email": "test@gmail.com", 
    "name": "Testing", 
    "parentCustomerId": "myCustomerId3", 
    "phoneNumber": "1111111111", 
    "primaryContactUserId": "primaryContactUserId", 
    "status": "ACTIVE", 
    "xylemPrimaryContactId": "testing" 
}

添加“childrenCustomerIds”:[“testing”]

Object.assign(obj, {"childrenCustomerIds": ["testing"]});

同样,您可以添加“属性”:{}

Object.assign(obj, {"properties": {}});

【讨论】:

  • 感谢您的解决方案,但我认为这种方法是 ES5 方法,但我可以在 ES6/Typescript 中看到我无法完全理解的接口概念。如果您有任何 ES6/Typescript 解决方案,我将不胜感激。
  • Object.assign() 是 ES6/Typescript 功能,仅用于使用接口克隆等更多细节,请查看stackoverflow.com/questions/22885995/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 2020-06-21
  • 2018-11-06
  • 2017-11-04
  • 1970-01-01
  • 2020-03-27
相关资源
最近更新 更多