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

如何批量为对象成员执行JavaScript Nullish赋值(??=)操作?

问题描述

现有如下两个JavaScript对象:

foo = {
  a: 10,
  b: 'hello',
  c: 'world'
}

bar = {
  a:5,
  b: null,
  c: null,
  d: "This is not in foo"
}

希望实现等效于以下代码的操作,但无需逐个指定对象成员:

bar.a ??= foo.a
bar.b ??= foo.b
bar.c ??= foo.c

console.log(bar) // {a:5, b:'hello', c:'world', d:'This is not in foo'}

核心需求:遍历bar的每个成员,若该成员为nullish(null或undefined),则取foo中的对应值;foo中存在但bar中没有的成员保持不变(不添加到bar)。尝试过解构赋值但没找到解决方案,该如何实现?

实现方案

方案一:原地修改原对象

通过遍历bar的所有键,结合nullish赋值操作符直接更新原对象,逻辑和你手动逐个赋值完全一致:

for (const key in bar) {
  bar[key] ??= foo[key];
}

console.log(bar); // {a:5, b:'hello', c:'world', d:'This is not in foo'}

方案二:生成新对象(不修改原对象)

如果需要保留原始bar对象的内容,可以用Object.entries和Object.fromEntries创建新对象:

const updatedBar = Object.fromEntries(
  Object.entries(bar).map(([key, val]) => [key, val ?? foo[key]])
);

console.log(updatedBar); // {a:5, b:'hello', c:'world', d:'This is not in foo'}

关键说明

  • ??和??=仅针对nullish值(null或undefined)触发赋值,完全匹配你的需求;
  • 两种方案都只会处理bar已存在的键,不会把foo中额外的键添加到bar里,符合“foo中存在但bar中没有的成员保持不变”的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:35:26