javascript - 如何从嵌套的对象数组中获取每个父级的值
问题描述
所以我有多个对象数组,每个对象都包含一个孩子。
例如
const data = [
{
id: 1,
name: 'parent 1',
children: [
{
id: 'c1',
name: 'child 1',
children: [
{
id: 'g1',
name: 'grand 1',
children: [],
},
],
},
],
},
{
id: 2,
name: 'parent 2',
children: [
{
id: 2,
name: 'c1',
children: [],
},
],
},
{ id: 3, name: 'parent 3', children: [] },
];
我想要发生的是,如果我正在搜索的 Id 是“g1”,我会得到结果
const result = ['parent 1', 'c1', 'grand 1']
循环只会停止并获取它通过的所有名称,直到满足条件(在本例中为 id)
当前方法已完成
/**
* Details
* @param id the value you are searching for
* @param items nested array of object that has child
* @param key name of the value you are looking for
* @returns string of array that matches the id
* @example ['parent 1', 'c1', 'grand 1']
*/
export function findAll(id: string, items: any, key: string): string[] {
let i = 0;
let found;
let result = [];
for (; i < items.length; i++) {
if (items[i].id === id) {
result.push(items[i][key]);
} else if (_.isArray(items[i].children)) {
found = findAll(id, items[i].children, key);
if (found.length) {
result = result.concat(found);
}
}
}
return result;
}
解决方案
我编写了这段迭代代码,可能会对您有所帮助。它基本上遍历存储从顶层到所需 id 的路径的结构:
function getPath(obj, id) {
// We need to store path
// Start stack with root nodes
let stack = obj.map(item => ({path: [item.name], currObj: item}));
while (stack.length) {
const {path, currObj} = stack.pop()
if (currObj.id === id) {
return path;
} else if (currObj.children?.length) {
stack = stack.concat(currObj.children.map(item => ({path: path.concat(item.name), currObj: item})));
}
}
return null; // if id does not exists
}
此代码假定您的结构是正确的并且没有遗漏任何部分(可以为空的子代除外)。顺便说一句,你的答案正确吗?我想路径应该是:
["parent 1", "child 1", "grand 1"]
推荐阅读
- swiftui - SwiftUI - 带有私有变量的 PreviewProvider
- rpa - UiPath 搜索亚马逊中不可用的项目并显示未找到的项目
- android-studio - 使用 3rd 方库将表情符号添加到我的 android 自定义键盘
- api - 新 API 版本的标准
- spring-boot - 执行服务时假装客户端异常中的多个@RequestBody
- angular - 如何在 ng2-date-picker 中打开图标单击角度?
- html - display:none 在移动设备上无法正常工作
- javascript - 函数 __doPostBack() 在 iOS、iPadOS 浏览器中不起作用
- php - php setcookie 在安卓手机上不起作用
- azure-functions - 使用 B2C 自定义策略调用 Azure Function 时如何发送电子邮件?