Angular中查找匹配id/name的对象并修改对应show属性值
实现方法
首先先修正你给出的示例数据里的语法问题:对象属性之间需要用逗号分隔,原代码中show属性后用了分号,会报语法错误,修正后的基础数据如下:
const data = [ { id: 1, name: 'one', show: false, title: 'title1', data: [ { id: 1, description: 'some description' }, { id: 2, description: 'some other description' } ] }, { id: 2, name: 'two', show: true, title: 'title2', data: [ { id: 1, description: 'some description' }, { id: 2, description: 'some other description' } ] } ]
单层数组场景(仅匹配一级数组项)
如果只需要查找最外层数组的匹配项,直接遍历判断即可,封装成通用函数如下:
/** * 更新数组中匹配项的show属性 * @param {Array} targetList 待检索的对象数组 * @param {string|number} matchKeyVal 要匹配的id/name值 * @param {boolean} newShowVal show字段要设置的新值 * @returns {boolean} 是否成功找到并修改匹配项 */ function updateShowValue(targetList, matchKeyVal, newShowVal) { for (const item of targetList) { // 同时匹配id和name字段,不需要匹配某一个的话直接删掉对应判断即可 if (item.id === matchKeyVal || item.name === matchKeyVal) { item.show = newShowVal; // 匹配值唯一的话找到第一个就终止遍历,性能更好;要修改所有匹配项就删掉这行return return true; } } return false; } // 调用示例:查找id为2的条目,将show改为false updateShowValue(data, 2, false);
嵌套数组场景(递归检索所有层级的子数组)
如果你需要同时匹配每个项内部data子数组里的条目,用递归版本即可:
function updateNestedShowValue(targetList, matchKeyVal, newShowVal) { let hasUpdated = false; for (const item of targetList) { if (item.id === matchKeyVal || item.name === matchKeyVal) { item.show = newShowVal; hasUpdated = true; } // 存在子数组则递归处理 if (Array.isArray(item.data)) { const childRes = updateNestedShowValue(item.data, matchKeyVal, newShowVal); hasUpdated = hasUpdated || childRes; } } return hasUpdated; }
注意事项
- 上述实现默认直接修改原数据,如果不想产生原数据变更的副作用,操作前先对原数组做深拷贝即可。
- 可以根据业务需求调整判断逻辑,比如只需要按id匹配就删掉name的判断条件,反之同理。
- 如果数组数据量很大,找到目标项后立刻终止遍历能减少不必要的性能消耗,不需要遍历完整个数组。
内容的提问来源于stack exchange,提问作者pixelKus2022
相关产品推荐
相关产品推荐

