用另一个对象替换对象

时间:2018-12-06 12:42:11

标签: angular typescript

我有一个包含和地址对象的组织对象,我想用从表单中获取的值来编辑地址对象,然后我要用新的对象地址来更改组织对象中的地址对象,所以我使用了Object.assign,但是它总是返回旧地址

export class Organization {
    public address?: Address;
    public telecoms?: Telecom[];
    public metier?: Dictionary;
}

export class Address {
    public zipCode?: Dictionary;
    public country?: Dictionary;
    public city?: string;
}

export class Dictionary {
    public id?: number;
    public code?: string;
    public label?: string;
}

this.organizationService.getOneById(this.id).subscribe((organization: Organization) => this.organization= organization });

const address = this.editForm.get("address").value;

console.log(JSON.stringify({ address })); // {"address":{"country":{"id":2},"zipCode":{"id":1}}} 

let organiationToSave: Organization = this.organization;

Object.assign({}, organiationToSave , JSON.stringify({ address }));

console.log(organiationToSave); 

1 个答案:

答案 0 :(得分:2)

Object.assign({}, organiationToSave , JSON.stringify({ address }));

console.log(organiationToSave);

在上面的代码中,您正在为新对象{}分配值,然后登录organiationToSave。这没有道理。

也许您想这样做吗?

const obj = Object.assign({}, organiationToSave , JSON.stringify({ address }));

console.log(obj);

或者,如果您要更新organiationToSave,请执行以下操作:

Object.assign(organiationToSave , JSON.stringify({ address }));

console.log(organiationToSave);