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

如何使用map和find修改原变量中对象数组的joined字段(非true设为null)

原地修改hobbies数组的joined字段(用map和find实现)

首先先看你的原始对象:

const kids = { 
  name: 'john', 
  extra: { 
    city: 'London', 
    hobbies: [ 
      { id: 'football', team: 'ABC', joined: true }, 
      { id: 'basketball', team: 'DEF', joined: false }, 
      { id: 'volleyball', team: 'DEF', joined: null }, 
    ], 
  }, 
};

要实现原地修改(直接修改当前kids变量,不创建新对象/数组),同时用到map和find,可以这么做:

实现代码

// 用map遍历hobbies数组的每一项,触发修改逻辑
kids.extra.hobbies.map(hobby => {
  // 用find根据id精准匹配到原数组中的目标hobby对象
  const targetHobby = kids.extra.hobbies.find(item => item.id === hobby.id);
  // 修改joined字段:仅保留严格等于true的值,其余全部设为null
  if (targetHobby) {
    targetHobby.joined = targetHobby.joined === true ? true : null;
  }
});

逻辑说明

  • map的作用:这里我们利用map的遍历特性来遍历原hobbies数组的每一项——虽然map会返回一个新数组,但我们不需要这个返回值,只是用它来触发我们的修改逻辑。
  • find的作用:通过find根据id在原数组中找到对应的hobby对象(确保我们修改的是原数组里的元素,满足原地修改的要求)。
  • 字段修改规则:只有当joined的值**严格等于true**时才保留,其他任何值(false、null、undefined等)都统一设置为null。

验证结果

运行代码后,你打印kids.extra.hobbies会得到:

[
  { id: 'football', team: 'ABC', joined: true },
  { id: 'basketball', team: 'DEF', joined: null },
  { id: 'volleyball', team: 'DEF', joined: null }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:38:43