Related
I would like to loop through a deeply nested object, and sort each level based on a property. In this case its id
Here's my object (there will me more levels, I just added 3 levels here for readability):
const myObj = [
{
id: 15,
children: [
{
id: 9,
children: [
{
id: 4,
children: []
},
{
id: 1,
children: []
}
]
},
{
id: 4,
children: [
{
id: 35,
children: [
{
id: 12,
children: []
},
{
id: 8,
children: []
}
]
},
{
id: 30,
children: [],
}
]
},
]
},
{
id: 2,
children: [
{
id: 9,
children: []
},
{
id: 3,
children: []
},
]
}
]
Here's the desired output:
const myObj = [
{
id: 2,
children: [
{
id: 3,
children: []
},
{
id: 9,
children: []
}
]
},
{
id: 15,
children: [
{
id: 4,
children: [
{
id: 30,
children: [],
},
{
id: 35,
children: [
{
id: 8,
children: []
},
{
id: 12,
children: []
}
]
},
]
},
{
id: 9,
children: [
{
id: 1,
children: []
},
{
id: 4,
children: []
}
]
},
]
}
]
And here's my attempt at sorting it:
const myObj = [{id:15,children:[{id:9,children:[{id:4,children:[]},{id:1,children:[]}]},{id:4,children:[{id:35,children:[{id:12,children:[]},{id:8,children:[]}]},{id:30,children:[],}]},]},{id:2,children:[{id:9,children:[]},{id:3,children:[]},]}]
function sortByOrderIndex(obj) {
obj.sort((a, b) => (a.orderindex > b.orderindex) ? 1 : ((b.orderindex > a.orderindex) ? -1 : 0));
return obj;
}
function sortNestedObj(obj) {
sortByOrderIndex(obj);
for (let i = 0; i < obj.length; i++) {
const t = obj[i];
if (t.children.length !== 0) {
sortNestedObj(t.children);
} else {
return;
}
}
}
console.log(sortByOrderIndex(myObj))
I've created a function that sorts an object, and then tried to create another object that loops through each object that has children and sort those children using the first function. And if those children have children, then sort those and so forth until a child has no children.
You could recursively sort the array and it's object's children like this:
const myObj = [{id:15,children:[{id:9,children:[{id:4,children:[]},{id:1,children:[]}]},{id:4,children:[{id:35,children:[{id:12,children:[]},{id:8,children:[]}]},{id:30,children:[],}]},]},{id:2,children:[{id:9,children:[]},{id:3,children:[]},]}]
function sortArray(array) {
array.sort((a, b) => a.id - b.id);
array.forEach(a => {
if (a.children && a.children.length > 0)
sortArray(a.children)
})
return array;
}
console.log(sortArray(myObj))
You can make a recursive sorting function:
const myObj = [{id:15,children:[{id:9,children:[{id:4,children:[]},{id:1,children:[]}]},{id:4,children:[{id:35,children:[{id:12,children:[]},{id:8,children:[]}]},{id:30,children:[],}]},]},{id:2,children:[{id:9,children:[]},{id:3,children:[]},]}]
const orderChildren = obj => {
obj.children.sort((a, b) => a.id - b.id);
if (obj.children.some(o => o.children.length)) {
obj.children.forEach(child => orderChildren(child));
}
return obj;
};
const myNewObj = myObj.map(o => orderChildren(o)).sort((a, b) => a.id - b.id);
console.log(myNewObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do:
const myObj = [{id: 15,children: [{id: 9,children: [{id: 4,children: []},{id: 1,children: []}]},{id: 4,children: [{id: 35,children: [{id: 12,children: []},{id: 8,children: []}]},{id: 30,children: [],}]},]},{id: 2,children: [{id: 9,children: []},{id: 3,children: []},]}];
const deepSortById = arr => (arr.forEach(a => a.children && deepSortById(a.children)), arr.sort((a, b) => a.id - b.id));
const result = deepSortById(myObj);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I created generic solution for sorting nested arrays by id. My solution works with any nested array and sorts it according to id property. Or by any other property you specify in the method's seconds parameter.
function sortNestedArrays(obj, sortPropertyName) {
Object.keys(obj).forEach((key) => {
if (Array.isArray(obj[key])) {
obj[key].sort((a, b) => a[sortPropertyName] - b[sortPropertyName]);
}
if (!!obj[key] && (typeof obj[key] === 'object' || Array.isArray(obj[key]))) {
sortNestedArrays(obj[key], sortPropertyName);
}
});
return obj;
}
Usage is following:
obj = sortNestedArrays(obj, 'id');
How would I find all values by specific key in a deep nested object?
For example, if I have an object like this:
const myObj = {
id: 1,
children: [
{
id: 2,
children: [
{
id: 3
}
]
},
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6,
children: [
{
id: 7,
}
]
}
]
}
]
},
]
}
How would I get an array of all values throughout all nests of this obj by the key of id.
Note: children is a consistent name, and id's won't exist outside of a children object.
So from the obj, I would like to produce an array like this:
const idArray = [1, 2, 3, 4, 5, 6, 7]
This is a bit late but for anyone else finding this, here is a clean, generic recursive function:
function findAllByKey(obj, keyToFind) {
return Object.entries(obj)
.reduce((acc, [key, value]) => (key === keyToFind)
? acc.concat(value)
: (typeof value === 'object')
? acc.concat(findAllByKey(value, keyToFind))
: acc
, [])
}
// USAGE
findAllByKey(myObj, 'id')
You could make a recursive function like this:
idArray = []
function func(obj) {
idArray.push(obj.id)
if (!obj.children) {
return
}
obj.children.forEach(child => func(child))
}
Snippet for your sample:
const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
}
idArray = []
function func(obj) {
idArray.push(obj.id)
if (!obj.children) {
return
}
obj.children.forEach(child => func(child))
}
func(myObj)
console.log(idArray)
I found steve's answer to be most suited for my needs in extrapolating this out and creating a general recursive function. That said, I encountered issues when dealing with nulls and undefined values, so I extended the condition to accommodate for this. This approach uses:
Array.reduce() - It uses an accumulator function which appends the value's onto the result array. It also splits each object into it's key:value pair which allows you to take the following steps:
Have you've found the key? If so, add it to the array;
If not, have I found an object with values? If so, the key is possibly within there. Keep digging by calling the function on this object and append the result onto the result array; and
Finally, if this is not an object, return the result array unchanged.
Hope it helps!
const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
}
function findAllByKey(obj, keyToFind) {
return Object.entries(obj)
.reduce((acc, [key, value]) => (key === keyToFind)
? acc.concat(value)
: (typeof value === 'object' && value)
? acc.concat(findAllByKey(value, keyToFind))
: acc
, []) || [];
}
const ids = findAllByKey(myObj, 'id');
console.log(ids)
You can make a generic recursive function that works with any property and any object.
This uses Object.entries(), Object.keys(), Array.reduce(), Array.isArray(), Array.map() and Array.flat().
The stopping condition is when the object passed in is empty:
const myObj = {
id: 1,
anyProp: [{
id: 2,
thing: { a: 1, id: 10 },
children: [{ id: 3 }]
}, {
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{ id: 7 }]
}]
}]
}]
};
const getValues = prop => obj => {
if (!Object.keys(obj).length) { return []; }
return Object.entries(obj).reduce((acc, [key, val]) => {
if (key === prop) {
acc.push(val);
} else {
acc.push(Array.isArray(val) ? val.map(getIds).flat() : getIds(val));
}
return acc.flat();
}, []);
}
const getIds = getValues('id');
console.log(getIds(myObj));
Note: children is a consistent name, and id's wont exist outside
of a children object.
So from the obj, I would like to produce an array like this:
const idArray = [1, 2, 3, 4, 5, 6, 7]
Given that the question does not contain any restrictions on how the output is derived from the input and that the input is consistent, where the value of property "id" is a digit and id property is defined only within "children" property, save for case of the first "id" in the object, the input JavaScript plain object can be converted to a JSON string using JSON.stringify(), RegExp /"id":\d+/g matches the "id" property and one or more digit characters following the property name, which is then mapped to .match() the digit portion of the previous match using Regexp \d+ and convert the array value to a JavaScript number using addition operator +
const myObject = {"id":1,"children":[{"id":2,"children":[{"id":3}]},{"id":4,"children":[{"id":5,"children":[{"id":6,"children":[{"id":7}]}]}]}]};
let res = JSON.stringify(myObject).match(/"id":\d+/g).map(m => +m.match(/\d+/));
console.log(res);
JSON.stringify() replacer function can alternatively be used to .push() the value of every "id" property name within the object to an array
const myObject = {"id":1,"children":[{"id":2,"children":[{"id":3}]},{"id":4,"children":[{"id":5,"children":[{"id":6,"children":[{"id":7}]}]}]}]};
const getPropValues = (o, prop) =>
(res => (JSON.stringify(o, (key, value) =>
(key === prop && res.push(value), value)), res))([]);
let res = getPropValues(myObject, "id");
console.log(res);
Since the property values of the input to be matched are digits, all the JavaScript object can be converted to a string and RegExp \D can be used to replace all characters that are not digits, spread resulting string to array, and .map() digits to JavaScript numbers
let res = [...JSON.stringify(myObj).replace(/\D/g,"")].map(Number)
Using recursion.
const myObj = { id: 1, children: [ { id: 2, children: [ { id: 3 } ] }, { id: 4, children: [ { id: 5, children: [ { id: 6, children: [ { id: 7, } ] } ] } ] }, ]},
loop = (array, key, obj) => {
if (!obj.children) return;
obj.children.forEach(c => {
if (c[key]) array.push(c[key]); // is not present, skip!
loop(array, key, c);
});
},
arr = myObj["id"] ? [myObj["id"]] : [];
loop(arr, "id", myObj);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can make a recursive function with Object.entries like so:
const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
};
function findIds(obj) {
const entries = Object.entries(obj);
let result = entries.map(e => {
if (e[0] == "children") {
return e[1].map(child => findIds(child));
} else {
return e[1];
}
});
function flatten(arr, flat = []) {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, flat);
} else {
flat.push(value);
}
}
return flat;
}
return flatten(result);
}
var ids = findIds(myObj);
console.log(ids);
Flattening function from this answer
ES5 syntax:
var myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
};
function findIds(obj) {
const entries = Object.entries(obj);
let result = entries.map(function(e) {
if (e[0] == "children") {
return e[1].map(function(child) {
return findIds(child)
});
} else {
return e[1];
}
});
function flatten(arr, flat = []) {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, flat);
} else {
flat.push(value);
}
}
return flat;
}
return flatten(result);
}
var ids = findIds(myObj);
console.log(ids);
let str = JSON.stringify(myObj);
let array = str.match(/\d+/g).map(v => v * 1);
console.log(array); // [1, 2, 3, 4, 5, 6, 7]
We use object-scan for a lot of our data processing needs now. It makes the code much more maintainable, but does take a moment to wrap your head around. Here is how you could use it to answer your question
// const objectScan = require('object-scan');
const find = (data, needle) => objectScan([needle], { rtn: 'value' })(data);
const myObj = { id: 1, children: [{ id: 2, children: [ { id: 3 } ] }, { id: 4, children: [ { id: 5, children: [ { id: 6, children: [ { id: 7 } ] } ] } ] }] };
console.log(find(myObj, '**.id'));
// => [ 7, 6, 5, 4, 3, 2, 1 ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
import {flattenDeep} from 'lodash';
/**
* Extracts all values from an object (also nested objects)
* into a single array
*
* #param obj
* #returns
*
* #example
* const test = {
* alpha: 'foo',
* beta: {
* gamma: 'bar',
* lambda: 'baz'
* }
* }
*
* objectFlatten(test) // ['foo', 'bar', 'baz']
*/
export function objectFlatten(obj: {}) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(objectFlatten(value));
} else {
result.push(value);
}
}
return flattenDeep(result);
}
Below solution is generic which will return all values by matching nested keys as well e.g for below json object
{
"a":1,
"b":{
"a":{
"a":"red"
}
},
"c":{
"d":2
}
}
to find all values matching key "a" output should be return
[1,{a:"red"},"red"]
const findkey = (obj, key) => {
let arr = [];
if (isPrimitive(obj)) return obj;
for (let [k, val] of Object.entries(obj)) {
if (k === key) arr.push(val);
if (!isPrimitive(val)) arr = [...arr, ...findkey(val, key)];
}
return arr;
};
const isPrimitive = (val) => {
return val !== Object(val);
};
I need to filter objects recursively in a deeply nested array of objects using javascript, maybe with the help of lodash.
What is the cleanest way to do it, If I don't know how many nested object there will be in my array?
Let's say I have the following structure
[
{
label: "first",
id: 1,
children: []
},
{
label: "second",
id: 2,
children: [
{
label: "third",
id: 3,
children: [
{
label: "fifth",
id: 5,
children: []
},
{
label: "sixth",
id: 6,
children: [
{
label: "seventh",
id: 7,
children: []
}
]
}
]
},
{
label: "fourth",
id: 4,
children: []
}
]
}
];
I want to find the one with id 6, and if it has children return true otherwise false.
Of course If I have a similar data structure but with different number of items it should work too.
Since you only want a true of false answer you can use some() on the recursion, effectively doing a depth-first search, and make it pretty succinct:
let arr = [{label: "first",id: 1,children: []},{label: "second",id: 2,children: [{label: "third",id: 3,children: [{label: "fifth",id: 5,children: []},{label: "sixth",id: 6,children: [{label: "seventh",id: 7,children: []}]}]},{label: "fourth",id: 4,children: []}]}];
function findNested(arr, id) {
let found = arr.find(node => node.id === id)
return found
? found.children.length > 0
: arr.some((c) => findNested(c.children, id))
}
console.log(findNested(arr, 6)) // True: found with children
console.log(findNested(arr, 7)) // False: found no children
console.log(findNested(arr, 97)) // False: not found
Perhaps a recursive solution along the lines of this might work for you? Here, the node with supplied id is recursively searched for through the 'children' of the supplied input data. If a child node with matching id is found, a boolean result is returned based on the existence of data in that nodes children array:
function nodeWithIdHasChildren(children, id) {
for(const child of children) {
// If this child node matches supplied id, then check to see if
// it has data in it's children array and return true/false accordinly
if(child.id === id) {
if(Array.isArray(child.children) && child.children.length > 0) {
return true
}
else {
return false
}
}
else {
const result = nodeWithIdHasChildren(child.children, id);
// If result returned from this recursion branch is not undefined
// then assume it's true or false from a node matching the supplied
// id. Pass the return result up the call stack
if(result !== undefined) {
return result
}
}
}
}
const data = [
{
label: "first",
id: 1,
children: []
},
{
label: "second",
id: 2,
children: [
{
label: "third",
id: 3,
children: [
{
label: "fifth",
id: 5,
children: []
},
{
label: "sixth",
id: 6,
children: [
{
label: "seventh",
id: 7,
children: []
}
]
}
]
},
{
label: "fourth",
id: 4,
children: []
}
]
}
];
console.log('node 6 has children:', nodeWithIdHasChildren( data, 6 ) )
console.log('node 7 has children:', nodeWithIdHasChildren( data, 7 ) )
console.log('node 100 has children:', nodeWithIdHasChildren( data, 7 ), '(because node 100 does not exist)' )
Here is another solution using recursion and doing it via only one Array.find:
const data = [ { label: "first", id: 1, children: [] }, { label: "second", id: 2, children: [ { label: "third", id: 3, children: [ { label: "fifth", id: 5, children: [] }, { label: "sixth", id: 6, children: [ { label: "seventh", id: 7, children: [] } ] } ] }, { label: "fourth", id: 4, children: [] } ] } ];
const search = (data, id) => {
var f, s = (d, id) => d.find(x => x.id == id ? f = x : s(x.children, id))
s(data, id)
return f ? f.children.length > 0 : false
}
console.log(search(data, 6)) // True: found with children
console.log(search(data, 7)) // False: found but has no children
console.log(search(data, 15)) // False: not found at all
The idea is to have a recursive function which when finds the id remembers the object.
Once we have the found (or we know we do not have an entry found) just return the children array length or return false.
If you want to actually return the found object instead of the boolean for children.length:
const data = [ { label: "first", id: 1, children: [] }, { label: "second", id: 2, children: [ { label: "third", id: 3, children: [ { label: "fifth", id: 5, children: [] }, { label: "sixth", id: 6, children: [ { label: "seventh", id: 7, children: [] } ] } ] }, { label: "fourth", id: 4, children: [] } ] } ];
const search = (data, id) => {
var f, s = (d, id) => d.find(x => x.id == id ? f = x : s(x.children, id))
s(data, id)
return f
}
console.log(search(data, 6)) // returns only the object with id:6
console.log(search(data, 7)) // returns only the object with id: 7
console.log(search(data, 71)) // returns undefined since nothing was found
You can use "recursion" like below to check if id has children or not
let arr = [{label: "first",id: 1,children: []},{label: "second",id: 2,children: [{label: "third",id: 3,children: [{label: "fifth",id: 5,children: []},{label: "sixth",id: 6,children: [{label: "seventh",id: 7,children: []}]}]},{label: "fourth",id: 4,children: []}]}];
function hasChildren(arr, id) {
let res = false
for (let d of arr) {
if(d.id == id) return d.children.length > 0
res = res || hasChildren(d.children, id)
if(res) return true
}
return res
}
console.log('id 4 has children? ', hasChildren(arr, 4))
console.log('id 6 has children? ', hasChildren(arr, 6))
You can do it using three simple javascript functions:
// Function to Flatten results
var flattenAll = function(data) {
var result = [];
var flatten = function(arr) {
_.forEach(arr, function(a) {
result.push(a);
flatten(a.children);
});
};
flatten(data);
return result;
};
// Function to search on flattened array
var search = function(flattened, id) {
var found = _.find(flattened, function(d) {
return d.id == id;
});
return found;
};
// Function to check if element is found and have children
var hasChildren = function(element) {
return element && element.children && element.children.length > 0;
}
// Usage, search for id = 6
hasChildren(search(flattenAll(your_data_object), 6))
Plunker
You can use a generator function to iterate the nodes recursively and simplify your logic for checking existence by using Array.prototype.some():
const data = [{label:'first',id:1,children:[]},{label:'second',id:2,children:[{label:'third',id:3,children:[{label:'fifth',id:5,children:[]},{label:'sixth',id:6,children:[{label:'seventh',id:7,children:[]}]}]},{label:'fourth',id:4,children:[]}]}];
function * nodes (array) {
for (const node of array) {
yield node;
yield * nodes(node.children);
}
}
const array = Array.from(nodes(data));
console.log(array.some(node => node.id === 6 && node.children.length > 0));
console.log(array.some(node => node.id === 7 && node.children.length > 0));
The JSON.parse reviver parameter or the JSON.stringify replacer parameter can be used to check all values, and generate flat id lookup object with references to the nodes :
var lookup = {}, json = '[{"label":"first","id":1,"children":[]},{"label":"second","id":2,"children":[{"label":"third","id":3,"children":[{"label":"fifth","id":5,"children":[]},{"label":"sixth","id":6,"children":[{"label":"seventh","id":7,"children":[]}]}]},{"label":"fourth","id":4,"children":[]}]}]'
var result = JSON.parse(json, (key, val) => val.id ? lookup[val.id] = val : val);
console.log( 'id: 2, children count:', lookup[2].children.length )
console.log( 'id: 6, children count:', lookup[6].children.length )
console.log( lookup )
I suggest to use deepdash extension for lodash:
var id6HasChildren = _.filterDeep(obj,
function(value, key, parent) {
if (key == 'children' && parent.id == 6 && value.length) return true;
},
{ leavesOnly: false }
).length>0;
Here is a docs for filterDeep.
And this a full test for your case.
We now use object-scan for data processing needs like this. It's very powerful once you wrap your head around it. This is how you could solve your questions
// const objectScan = require('object-scan');
const hasChildren = (e) => e instanceof Object && Array.isArray(e.children) && e.children.length !== 0;
const find = (id, input) => {
const match = objectScan(['**'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.id === id
})(input);
return hasChildren(match);
};
const data = [{ label: 'first', id: 1, children: [] }, { label: 'second', id: 2, children: [{ label: 'third', id: 3, children: [{ label: 'fifth', id: 5, children: [] }, { label: 'sixth', id: 6, children: [{ label: 'seventh', id: 7, children: [] }] }] }, { label: 'fourth', id: 4, children: [] }] }];
console.log(find(6, data));
// => true
console.log(find(2, data));
// => true
console.log(find(7, data));
// => false
console.log(find(999, data));
// => false
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
The first object{array}, the one i want to filter :
const object1 = {
"count" : 2,
"result" : [
{ "id": 1 },
{ "id": 2 }
]
}
The second array :
const array2 = [{
"id": 1,
"id": 44
}]
I want to filter the first array object1.result (or create a new array apart from it) if object.result[i].id is equal to array2[i].id , an reduce the number of array count object1.count based on the number of filter element.
in the example above I should have a new object :
theNewObject = {
"count" : 1,
"result" : [
{ "id": 2 }
]
}
You could use a Set an collect all id for filtering.
var object = { count : 2, result : [{ id: 1 }, { id: 2 }] },
array = [{ id: 1 }, { id: 44 }],
ids = new Set(array.map(({ id }) => id));
object.result = object.result.filter(({ id }) => ids.has(id));
object.count = object.result.length;
console.log(object);
An approach which counts down the count.
var object = { count : 2, result : [{ id: 1 }, { id: 2 }] },
array = [{ id: 1 }, { id: 44 }],
ids = new Set(array.map(({ id }) => id));
object.result = object.result.filter(({ id }) => ids.has(id) || !object.count--);
console.log(object);
You can combine the filter() method with the find() method:
const object1 = {
count: 2,
result: [
{ id: 1 },
{ id: 2 },
],
};
const array2 = [
{ id: 1 },
{ id: 4 },
];
const filteredResult = object1.result.filter(({ id }) => !array2.find(x => x.id === id));
const object3 = {
count: filteredResult.length,
result: filteredResult,
};
console.log(object3);
The { id } syntax is destructuring assignment.
You can also use reduce():
const object1 = {
count: 2,
result: [
{ id: 1 },
{ id: 2 },
],
};
const array2 = [
{ id: 1 },
{ id: 4 },
];
const object3 = object1.result.reduce(
({ count, result }, { id }) => array2.find(x => x.id === id)
? ({ count, result })
: ({ count: count + 1, result: result.concat([{ id }]) }),
{ count: 0, result: [] },
);
console.log(object3);
I have Javascript tree structure
const tree = [
{id: 120 , children:[]},
{id: 110 , children:[
{id: 12 , children:[
{id: 3 , children:[]},
{id: 4 , children:[]}
]}
]},
{id: 10 , children:[
{id: 13 , children:[]}
]}
]
and i have this function to find the parent of given node
const _findParent = (tree, component, _parent) => {
let parent = null
// iterate
tree.forEach(node => {
if(node.id === component.id){
return _parent
}
parent = node. children ? _findParent(node.children, component, node) : parent
})
return parent
}
but it returns null, I cant find where i miss the parent object.
Basically you check the children, but your children is always an array which is a truthy value. In this case, you could check if children is an array.
The use of Array#forEach does not work with a return value for using outside of the callback.
I suggest to use Array#some, which allows an early exit, which is necessary if a node is found.
Then I suggest to use a second variable for getting a nested result and if truthy, then assign to parent for return and exit the iteration.
const _findParent = (tree, component, _parent) => {
let parent;
tree.some(node => {
var temp;
if (node.id === component.id) {
parent = _parent;
return true;
}
temp = Array.isArray(node.children) && _findParent(node.children, component, node);
if (temp) {
parent = temp;
return true;
}
});
return parent;
}
const tree = [{ id: 120, children: [] }, { id: 110, children: [{ id: 12, children: [{ id: 3, children: [] }, { id: 4, children: [] }] }] }, { id: 10, children: [{ id: 13, children: [] }] }];
console.log(_findParent(tree, { id: 4 }));
console.log(_findParent(tree, { id: 42 }));