Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  136] [ 4]  / answers: 1 / hits: 5172  / 3 Years ago, fri, august 27, 2021, 12:00:00

So I have a multiple array of object and each object my contain a child.


e.g


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: [] },
];

what I wanted to happen is that if the Id that I'm searching for is
'g1', I would get the result


const result = ['parent 1', 'c1', 'grand 1']

the loop would only stop and get all the names that it went thru until the condition, in this case the id, is met


current approach done


/**
* 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;
}


More From » arrays

 Answers
3

The solution below is a recursive function that does the search.




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',
},
],
},
{ id: 3, name: 'parent 3', children: [{}] },
];

function getPath(object, search) {
if (object.id === search) return [object.name];
else if ((object.children) || Array.isArray(object)) {
let children = Array.isArray(object) ? object : object.children;
for (let child of children) {
let result = getPath(child, search);
if (result) {
if (object.id )result.unshift(object.name);
return result;
}
}
}
}

//const result = ['parent 1', 'c1', 'grand 1']
const result = getPath(data, 'g1');
console.log(result);




[#955] Tuesday, August 17, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alyssiat

Total Points: 608
Total Questions: 102
Total Answers: 101

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
alyssiat questions
;