【发布时间】:2021-10-27 11:43:55
【问题描述】:
所以我有多个对象数组,每个对象都包含一个子对象。
例如
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;
}
【问题讨论】:
-
你试过什么?另外,
const result = 'parent 1' > 'c1' > 'grand 1'这是无效的数据对象,你可以验证你想要什么数据结构。 -
@ikhvjs,我更新了我想看的结果,谢谢评论
-
到目前为止你尝试过什么?我认为递归函数方法适合您的情况。
-
@ikhvjs,我尝试了这个,第三个答案,stackoverflow.com/questions/30714938/… 并进行了一些修改,但我似乎找不到将父母姓名存储在结果数组中的方法
-
你能告诉我们你的方法吗?
标签: javascript arrays typescript object