TypeScript中如何获取数组内key为text的对象value值?
解决TypeScript数组遍历索引类型错误问题
错误原因
Object.keys(txt)返回的是字符串类型的数组键(比如["0", "1", "2"]),但数组的索引要求是number类型,用字符串去索引数组就会触发Element implicitly has an 'any' type because index expression is not of type 'number'这个类型错误。
解决方案
方案1:直接遍历数组元素(最推荐)
数组自带的forEach可以直接遍历每个元素,不用处理索引,代码简洁且类型安全:
const txt = [ { key: 'topic', type: 'STRING', value: 'test' }, { key: 'key', type: 'STRING', value: '007' }, { key: 'text', type: 'STRING', value: 'I want to get this text' } ]; txt.forEach(item => { if (item.key === 'text') { console.log("Found.", item.value); // 直接拿到目标value } });
方案2:用find方法直接获取目标对象(更高效)
如果只需要第一个符合条件的对象,find方法一步到位,不用遍历整个数组:
const targetItem = txt.find(item => item.key === 'text'); if (targetItem) { console.log(targetItem.value); // 输出:I want to get this text }
方案3:修复原索引遍历写法(仅作参考)
如果一定要用索引遍历,需要把字符串键转成number类型:
Object.keys(txt).forEach(key => { const index = parseInt(key, 10); if (txt[index].key === 'text') { console.log("Found.", txt[index].value); } });
内容的提问来源于stack exchange,提问作者Pyyyyt
相关产品推荐
相关产品推荐

