**I have a tree of objects and I want to get the ids of all nodes whose check property is true and store them in an array,I used recursion, but no valid result, my data object is as follows
"id": "1000",
"parentId": "-1",
"check": true,
"children": [
{
"id": "2000",
"parentId": "1000",
"check": true,
"children": [
{
"id": "3000",
"parentId": "2000",
"check": true
},
{
"id": "3001",
"parentId": "2000",
"check": true
},
{
"id": "3002",
"parentId": "2000",
"check": false
}
]
}
]
},
{
"id": "1001",
"parentId": "-1",
"check": true,
"children": [
{
"id": "2001",
"parentId": "1001",
"check": true,
"children": [
{
"id": "3003",
"parentId": "2001",
"check": true
},
{
"id": "3004",
"parentId": "2001",
"check": true
},
{
"id": "3005",
"parentId": "2001",
"check": true
}
]
}
]
}
]
However, now I got an answer like this,Here's what I tried, but it's not what I ended up wanting
function getCheck(arr) {
let result = []
arr.forEach(item => {
if (item.check) {
result.push(item.id)
}
if (item.children) {
let child = getCheck(item.children)
if (child.length) {
result.push(child)
}
}
})
return result
}
What I want to get is
Is it possible to convert the above answer,Thanks for any suggestion.
CodePudding user response:
Let's use another variable (that defaults to []
) to store the path or depth we are currently at. Then, if the item has children, we get all the checks there and add them to the result, otherwise, that means we're at a leaf and we add the item's ID directly.
const data = [{"id":"1000","parentId":"-1","check":!0,"children":[{"id":"2000","parentId":"1000","check":!0,"children":[{"id":"3000","parentId":"2000","check":!0},{"id":"3001","parentId":"2000","check":!0},{"id":"3002","parentId":"2000","check":!1}]}]},{"id":"1001","parentId":"-1","check":!0,"children":[{"id":"2001","parentId":"1001","check":!0,"children":[{"id":"3003","parentId":"2001","check":!0},{"id":"3004","parentId":"2001","check":!0},{"id":"3005","parentId":"2001","check":!0}]}]}];
function getCheck(arr, path = []) {
let result = [];
arr.forEach(item => {
if (item.children) { // has children, not a leaf
// add all its children
result.push(...getCheck(item.children, [...path, item.id]));
} else { // no children, is leaf
result.push([...path, item.id]); // add its ID
}
});
return result;
}
console.log(getCheck(data));