2

I would like to know how to remove the status deleted in children key in a nested array of objects, in javascript, below code returns cannot return filter of undefined error, I have obj, children key should contain only status Active;

var obj = [
  {id:1, label: "sample", children: [{id: 0, status: "Active", name: "xyz"}, {id: 1, status: "Deleted", name: "abc"}]}
  {id:2, label: "example"},
  {id:3, label: "details", children: [{id:1, status: "Active", name: "finance"}]}
]

var result = removeDeleted(obj);

function removeDeleted(obj){
   if (obj.length > 0) {
    var list= obj.map(e => {
      e.children = e.children.map(child => {
        child.children = child.children.filter(c => 
          c['status'] !== "Deleted"       
        );
        return child
      });
      return e
    });
     return list;
  } 
}

Expected Output:
[
  {id:1, label: "sample", children: [{id: 0, status: "Active", name: "xyz"}]}
  {id:2, label: "example"},
  {id:3, label: "details", children: [{id:1, status: "Active", name: "finance"}]}
]


1
  • There is a case children may not exists for you in some objects of the array so just check with if condition before filter and map also. Commented May 26, 2020 at 4:40

2 Answers 2

1

You can try the following way:

var obj = [
  {id:1, label: "sample", children: [{id: 0, status: "Active", name: "xyz"}, {id: 1, status: "Deleted", name: "abc"}]},
  {id:2, label: "example"},
  {id:3, label: "details", children: [{id:1, status: "Active", name: "finance"}]}
]

var result = removeDeleted(obj);
console.log(result);
function removeDeleted(obj){
   return obj.map(i => {
     if(i.children){
        var c = i.children.filter(j => j.status != 'Deleted');
        return {id: i.id, label:i.label, children:c};
      }
     else return i;
   });
}

Sign up to request clarification or add additional context in comments.

Comments

0

If you have multiple properties, its better to destructure it.

var obj = [ {id:1, label: "sample", children: [{id: 0, status: "Active", name: "xyz"}, {id: 1, status: "Deleted", name: "abc"}]}, {id:2, label: "example"}, {id:3, label: "details", children: [{id:1, status: "Active", name: "finance"}]}];

var result = obj.map(({children, ...rest})=>{
    if(children) children = children.filter(({status})=>status=='Active');
    if(children) return {...rest, children};
    return rest
});

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.