You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何实现对象赋值并替换对象名称?

How to Create a 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 from res (your data.response.details) into it.
  • The result? newMember will be an exact duplicate of your original details object, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:31:35