如何使用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
相关产品推荐
相关产品推荐

