我有以下课程:
export class Son
{
public Field8_1 : number;
public Field8_2 : number;
}
export class Father
{
constructor (){
this.Field8 = new Son;
}
public Field1 : number;
public Field2 : number;
public Field3 : number;
public Field4 : number;
public Field5 : number;
public Field6 : number;
public Field7 : number;
Field8 : Son;
}
我必须使用Angular的HttpClient发送它。 所以我跑了:
var body = JSON.stringify(this.Father);
this.http.post (TGT_IP,body).subscribe (...)
我的尸体是:
{"Field8":{"Field8_1":81,"Field8_2":82},"Field1":1,"Field2":2,"Field3":3,"Field4":4,"Field5":5,"Field6":6,"Field7":7}
如何根据自己的需要“定制”字符串化以创建字符串:
"Field1":1,"Field2":2,"Field3":3,"Field4":4,"Field5":5,"Field6":6,"Field7","Field8_1":81, "Field8_2":82
我要发送“原始”字符串。
答案 0 :(得分:0)
您可以通过两种方式实现这一目标。方法一是使用散布运算符和儿子映射父亲的所有键,然后删除不需要的字段:
// First option
let mappedFather1 = {
...this.father,
Field8_1: this.father.Field8.Field8_1,
Field8_2: this.father.Field8.Field8_2
};
delete mappedFather1.Field8;
另一种选择是从本质上“挑选”所需的对象键:
// Second option
let mappedFather2 = {
Field1: this.father.Field1,
Field2: this.father.Field2,
Field3: this.father.Field3,
Field4: this.father.Field4,
Field5: this.father.Field5,
Field6: this.father.Field6,
Field7: this.father.Field7,
Field8_1: this.father.Field8.Field8_1,
Field8_2: this.father.Field8.Field8_2
}
如果不需要JSON的大括号,可以这样删除它们:
let noBracesFather = JSON.stringify(mappedFather1).substr(1).slice(0, -1);
这是一个堆栈闪电,将两个选项的输出记录到控制台,并删除括号:https://stackblitz.com/edit/angular-5wmz4c
显然,这假定父子对象的结构是已知的并且它们是静态的。