Angular 10中如何获取JSON响应内嵌套数组DisplayTags的长度
实现方案
1. 长度异常根因说明
你获取到的DisplayTags长度不符合预期,通常是两类原因导致:
- 未对
DisplayTags的空值/非数组类型做兜底,直接调用length属性返回非预期值 - 接口返回的
DisplayTags实际是JSON序列化后的字符串,而非数组,此时直接取length会拿到字符串的长度而非标签元素个数
2. 全场景兼容处理工具函数
以下JS函数可兼容DisplayTags为null、undefined、序列化字符串、正常数组的所有场景:
function getSafeDisplayTags(item) { // 初始兜底空数组 let tags = []; if (!item?.DisplayTags) return tags; // 若为字符串先尝试解析为数组 if (typeof item.DisplayTags === 'string') { try { const parsed = JSON.parse(item.DisplayTags); if (Array.isArray(parsed)) tags = parsed; } catch (e) { // 解析失败直接返回兜底空数组 } } else if (Array.isArray(item.DisplayTags)) { tags = item.DisplayTags; } // 可选:过滤空字符串、null等无效标签,保证长度更准确 return tags.filter(Boolean); }
3. 获取正确长度的方法
直接调用处理函数后取length属性即可:
// 示例:取第0条结果的标签长度 const tagsOfFirstItem = getSafeDisplayTags(CongnitiveSearchResult.value[0]); console.log(tagsOfFirstItem.length); // 输出标签实际个数
4. HTML循环渲染实现
原生JS实现
const tagContainer = document.getElementById('tag-container'); CongnitiveSearchResult.value.forEach(searchItem => { const safeTags = getSafeDisplayTags(searchItem); safeTags.forEach(tag => { const tagDiv = document.createElement('div'); tagDiv.className = 'tag-item'; tagDiv.innerText = tag; tagContainer.appendChild(tagDiv); }) })
Vue框架实现
<template> <div id="tag-container"> <div v-for="(searchItem, index) in CongnitiveSearchResult.value" :key="index"> <div v-for="(tag, tagIndex) in getSafeDisplayTags(searchItem)" :key="tagIndex" class="tag-item" > {{ tag }} </div> </div> </div> </template> <script> export default { methods: { getSafeDisplayTags(item) { // 复用上面的工具函数逻辑 } } } </script>
React框架实现
function TagRender({ CongnitiveSearchResult }) { const getSafeDisplayTags = (item) => { // 复用上面的工具函数逻辑 } return ( <div id="tag-container"> {CongnitiveSearchResult.value.map((searchItem, index) => ( <React.Fragment key={index}> {getSafeDisplayTags(searchItem).map((tag, tagIndex) => ( <div key={tagIndex} className="tag-item">{tag}</div> ))} </React.Fragment> ))} </div> ) }
内容的提问来源于stack exchange,提问作者user16575094
相关产品推荐
相关产品推荐

