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

能否通过解构赋值直接获取对象嵌套属性的newValue值?

利用嵌套解构赋值直接提取newValue

当然可以!不用循环,直接通过嵌套解构赋值就能一步完成这个需求,写法比重复赋值简洁得多:

const obj = {
  key1: {oldValue: '1', newValue: '2'},
  key2: {oldValue: '3', newValue: '4'},
  key3: {oldValue: '5', newValue: '6'},
}

// 嵌套解构直接提取newValue
const {
  key1: { newValue: key1 },
  key2: { newValue: key2 },
  key3: { newValue: key3 }
} = obj;

console.log(key1); // 输出 '2'
console.log(key2); // 输出 '4'
console.log(key3); // 输出 '6'

语法说明

这里的解构逻辑很直接:

  • 先从obj中取出key1、key2、key3这三个属性
  • 对每个属性的内部对象再做一层解构,取出其中的newValue,并将其重命名为和外层属性同名的变量

如果需要给变量起不同的名字,也可以灵活调整:

const {
  key1: { newValue: key1New },
  key2: { newValue: key2New },
  key3: { newValue: key3New }
} = obj;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:01:24