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

如何不明确指定属性名即可解构response1完成DTO构建?

优化实现方案

分两种场景选择合适的写法:

场景1:response1 仅包含你需要的 a、b、c 属性,无多余字段

直接用对象展开运算符即可,完全不需要显式写出三个属性名:

const dto = {
  ...JSON.parse(response1),
  otherObject: JSON.parse(response2)
};

这种写法代码最简洁,运行效率也最高。

场景2:response1 存在多余字段,仅需要提取 a、b、c 三个属性

你可以封装一个通用的属性提取工具函数,避免重复写属性名:

// 通用属性提取函数,可全局复用
const pick = (target, keys) => Object.fromEntries(
  keys.map(key => [key, target[key]])
);

// 构建DTO
const dto = {
  ...pick(JSON.parse(response1), ['a', 'b', 'c']),
  otherObject: JSON.parse(response2)
};

如果多余字段数量很少,也可以用剩余运算符过滤不需要的属性,比如response1里多余的属性是d、e:

const { d, e, ...res1Valid } = JSON.parse(response1);
const dto = {
  ...res1Valid,
  otherObject: JSON.parse(response2)
};

补充建议:原代码里的var可以替换为const,避免变量提升带来的意外问题。

内容的提问来源于stack exchange,提问作者Frank

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 06:15:05