如何提取JSON中父对象为parent4的所有ID属性值
提取指定父对象下的所有ID值
核心需求
从多层结构的JSON数据中,筛选出父对象为parent4的所有id值,最终得到数组:['this is needed1', 'this is needed2', 'this is needed3', 'this is needed4']。原有的findAllByKey会返回所有id,需要调整逻辑实现精准筛选。
解决方案1:先定位目标父节点,再提取所有ID
先找到parent4对应的节点,再递归遍历该节点下的所有子节点,收集id值:
// 假设你的JSON数据结构如下 const data = { // ... 其他无关层级 parent4: { id: 'this is needed1', child: { id: 'this is needed2', grandchild: { id: 'this is needed3' } }, anotherChild: { id: 'this is needed4' } } }; function getIdsUnderParent(targetParent, sourceData) { const ids = []; // 递归遍历节点收集ID function traverseNode(node) { for (const key in node) { if (key === 'id') { ids.push(node[key]); } else if (typeof node[key] === 'object' && node[key] !== null) { traverseNode(node[key]); } } } // 定位到目标父节点后开始遍历 if (sourceData[targetParent]) { traverseNode(sourceData[targetParent]); } return ids; } // 调用函数获取结果 const requiredIds = getIdsUnderParent('parent4', data); console.log(requiredIds); // 输出目标数组
解决方案2:修改递归函数,遍历中判断父节点
在递归遍历整个JSON的过程中,记录当前节点的父节点名称,仅收集目标父节点下的id:
function findIdsByParent(targetParent, sourceData) { const ids = []; function traverse(node, parentName) { for (const key in node) { if (key === 'id' && parentName === targetParent) { ids.push(node[key]); } else if (typeof node[key] === 'object' && node[key] !== null) { // 递归时传递当前节点的键名作为子节点的父节点名称 traverse(node[key], key); } } } traverse(sourceData, null); return ids; } // 调用函数获取结果 const requiredIds = findIdsByParent('parent4', data); console.log(requiredIds);
注意事项
- 请根据你的实际JSON结构调整
id的键名(如果你的ID键不是id,比如是ID或者其他名称,替换代码中对应的字符串即可)。 - 如果父节点不是通过键名标识,而是通过节点内的某个属性(比如
parent: 'parent4'),需要修改父节点的判断逻辑。
内容的提问来源于stack exchange,提问作者keerti
相关产品推荐
相关产品推荐

