如何在嵌套对象中检查指定值是否存在?解决TypeError报错
解决FreeCodeCamp唱片集挑战的重复值问题
我是编程新手,完成FreeCodeCamp的record-collection挑战后,希望扩展功能:当传入的value已存在时不执行任何操作。尝试使用hasOwnProperty()和indexOf()实现,但始终出现TypeError: Cannot read properties of undefined (reading 'indexOf')错误,求简洁解决办法。
原数据结构
// Setup const recordCollection = { 2548: { albumTitle: 'Slippery When Wet', artist: 'Bon Jovi', tracks: ['Let It Rock', 'You Give Love a Bad Name'] }, 2468: { albumTitle: '1999', artist: 'Prince', tracks: ['1999', 'Little Red Corvette'] }, 1245: { artist: 'Robert Palmer', tracks: [] }, 5439: { albumTitle: 'ABBA Gold' } };
原解决方案代码
function updateRecords(records, id, prop, value) { // Access target album in record collection const album = records[id]; // If value is an empty string, // delete the given prop property from the album if (value === "") { delete album[prop]; } // If prop isn't tracks, // update or set that album's prop to value else if (prop !== "tracks") { album[prop] = value; } // If prop is tracks, // add value to the end of the album's existing tracks array else { album["tracks"] = album["tracks"] || []; album["tracks"].push(value); } // Your function must always return the entire record collection object return records; }
简洁修改方案
报错原因是直接对未初始化的tracks数组调用indexOf,我们只需要在执行修改前先判断值是否已存在,同时处理tracks可能不存在的情况:
function updateRecords(records, id, prop, value) { const album = records[id]; // 先处理value为空的情况 if (value === "") { delete album[prop]; return records; } // 非tracks属性:判断当前值是否等于目标value,是则直接返回 if (prop !== "tracks") { if (album[prop] === value) return records; album[prop] = value; } // tracks属性:先确保数组存在,再判断是否已包含value else { album.tracks = album.tracks || []; if (album.tracks.indexOf(value) !== -1) return records; album.tracks.push(value); } return records; }
关键修改点
- 对非
tracks属性:直接对比当前属性值和传入的value,相等则跳过修改 - 对
tracks属性:先通过album.tracks = album.tracks || []初始化空数组,再用indexOf检查是否已存在目标值,存在则直接返回 - 所有判断都放在修改操作前,一旦满足重复条件就直接返回原对象,不执行后续逻辑
内容的提问来源于stack exchange,提问作者KnowNothing
相关产品推荐
相关产品推荐

