I have the following:
function getitemfalse(){
$this.items = $this.users.filter( function(item) {
if(item.status === false ) {
return item;
if( item.children.length > 0 ){
item.children = getchildrem(item.children, false);
}
} });
},
getchildrem(node, status){
$children = node.filter( function(item) {
if(item.status === status ) {
return item;
if( item.children.length > 0 ){
item.children = getchildrem(item.children, status);
}
}});
return $children;
},
I would like it to loop through all children's children, etc (not just the top level). But I'm unclear on how I refer to the current child if I make that switch? I would no longer have to clarify the index position of the child. Any suggestions?
What am I doing wrong?
Not sure how your input look like. But make your function recursive to achieve the result.
See the Snippet below for flat output:
let users = [{name: "1", status: false, children: null}, {name: "2", status: false, children: null}, {name: "3", status: true, children: [{name: "5", status: false, children: null}]}, {name: "4", status: true, children: null}];
let items = [];
function getItem(_users, _status){
_users.forEach(_user=>{
if(_user.status!=_status && _user.children && _user.children.length > 0){
getItem(_user.children, _status);
}else if(_user.status==_status){
//_user.children = null; //You can make it null if you dont want children
items.push(_user);
}
});
return items;
}
console.log(getItem(users, false));
You can test it here also
EDIT 1
See the Snippet below for nested output:
let users = [
{
name: "1",
status: false,
children: [
{
name: "5",
status: true,
children:null
}
]
},
{
name: "2",
status: true,
children: [
{
name: "6",
status: false,
children:null
}
]
},
{
name: "3",
status: false,
children: [
{
name: "7",
status: true,
children:[
{
name: "9",
status: false,
children:null
}
]
}
]
},
{
name: "4",
status: false,
children: [
{
name: "8",
status: false,
children:[
{
name: "10",
status: true,
children:null
}
]
}
]
}
];
let items = [];
function getItem(_parent, _users, _status){
_users.forEach(_user=>{
if(_user.status == _status){
let newUser = Object.create(_user, {});
newUser.children = [];
_parent.push(newUser);
if(_user.children && _user.children.length > 0){
getItem(newUser.children, _user.children, _status);
}
}
});
return items;
}
console.log(getItem(items, users, false));
You can test it here also