如何在包含空对象的嵌套数组的子数组中查找最远的有效对象
实现方案
核心逻辑
- 首先约定有效对象判定规则:非空普通对象,通过判断
Object.keys(目标对象).length > 0实现 - 遍历主数组所有元素,对每个元素的
xPoints子数组倒序遍历,第一个匹配到的有效对象就是当前子数组位置最远的有效对象 - 全局记录所有子数组找到的最远有效对象索引,保留最大值对应的索引和所属主元素即可
可直接运行的JavaScript代码
// 原始嵌套数组数据 const sourceData = [{ "id": 0, "name": "Primary", "xPoints": [{ "id": 0, "name": "Untitledtest12", "type": "custom", "description": "" }, { "id": 1, "name": "asd", "description": "", "type": "custom" }, { "id": 2, "name": "asd", "description": "", "type": "custom" }, { "id": 3, "name": "asd123", "description": "", "type": "custom" }, { "id": 4, "name": "a", "description": "a", "type": "custom" }] }, { "id": 1, "name": "Untitled X Line", "xPoints": [ {}, {}, {}, {}, {}, { "id": 0, "name": "this is the farthest", "type": "custom", "description": "" }, {} ] }] // 初始化结果存储变量 let farthestResult = { maxIndex: -1, parentItem: null } // 遍历主数组所有元素 sourceData.forEach(parent => { const xPoints = parent.xPoints // 倒序遍历xPoints找最远的有效对象 for (let i = xPoints.length - 1; i >= 0; i--) { if (Object.keys(xPoints[i]).length > 0) { // 超过当前记录的最大索引就更新结果 if (i > farthestResult.maxIndex) { farthestResult.maxIndex = i farthestResult.parentItem = parent } break } } }) // 输出结果 console.log('所属主元素名称:', farthestResult.parentItem.name) console.log('0基索引:', farthestResult.maxIndex) console.log('1基计数位置:', farthestResult.maxIndex + 1)
输出结果
所属主元素名称: Untitled X Line 0基索引: 5 1基计数位置: 6
和你预期的结果完全匹配。
内容的提问来源于stack exchange,提问作者Hex
相关产品推荐
相关产品推荐

