TypeScript中如何实现对象赋值并替换对象名称?
newMember Object from data.response.details Using Object.assign Hey there, let's break down how to nail this exactly how you want it.
First, your core goal: make a fresh newMember object that copies all properties from data.response.details (replacing the original details object). Let's walk through what works, and adjust if needed.
Your Current Code (It's Already Correct!)
Your existing approach is actually spot-on for copying the details properties into newMember. Let's look at it again:
public after(args: IResult, data: any) { const res: IResult = data.response.details; const newMember = Object.assign({}, res); return Promise.resolve(this.getInformation(args, newMember)); }
Here's the breakdown:
Object.assign({}, res)creates a blank new object ({}) as the target, then copies every enumerable property fromres(yourdata.response.details) into it.- The result?
newMemberwill be an exact duplicate of your originaldetailsobject, which matches the structure you want:
{ "patientProfile": { "firstName": "Rob", "lastName": "ALLen", "memberStatus": "Active" } }
If You Need a Top-Level newMember Key
If you actually want to wrap this copied object into a parent object with a top-level "newMember" key (like your sample expected JSON shows), just tweak the code slightly:
public after(args: IResult, data: any) { const res: IResult = data.response.details; // Wrap the copied object into a parent with the "newMember" key const wrappedResult = { newMember: Object.assign({}, res) }; return Promise.resolve(this.getInformation(args, wrappedResult)); }
This will give you the exact JSON structure you listed:
{ "newMember": { "patientProfile": { "firstName": "Rob", "lastName": "ALLen", "memberStatus": "Active" } } }
Quick Heads-Up: Shallow vs. Deep Copy
One thing to note: Object.assign does a shallow copy. That means if patientProfile had nested objects inside it, those nested items would still reference the original ones from data.response.details. If you need a full deep copy (where even nested objects are duplicated), you could use JSON.parse(JSON.stringify(res)) for simple data structures, or a dedicated deep copy utility for more complex data (like functions or special types). But for your current example, a shallow copy is totally enough.
内容的提问来源于stack exchange,提问作者hussain

