Search code examples
javascriptarraysfilterflatmap

How do i perform an operation on a child element and return the parent?


I have an array like this

const array = [
  { 
    name: 'Parent Brand 1', 
    childBrands: [
      { name: 'Child Brand 1', status: 'active' },
      { name: 'Child Brand 2', status: 'discontinued' },
    ] 
  }
, { 
    name: 'Parent Brand 2',
    childBrands: [
      { name: 'Child Brand 1', status: 'discontinued' },
      { name: 'Child Brand 2', status: 'active' },
    ] 
  }
];

How do I make it so that it filters the child brands by status and returns the parent object? After filtering by 'active' status it should return something like this,

const array = [
  { 
    name: 'Parent Brand 1', 
    childBrands: [
      { name: 'Child Brand 1', status: 'active' },
    ] 
  }
, { 
    name: 'Parent Brand 2',
    childBrands: [
      { name: 'Child Brand 2', status: 'active' },
    ] 
  }
];

Using a flatMap and filter only returns the child elements when i need the parent object including the child element

{ "name": "Child Brand 1","status": "active" }

{ "name": "Child Brand 2","status": "active" }

Solution

  • Since you haven't posted any code it's hard to know how you would be using flatMap() in this case. You can simply map() over the array and filter each nested array property.

    const array = [{ name: 'Parent Brand 1', childBrands: [{ name: 'Child Brand 1', status: 'active' }, { name: 'Child Brand 2', status: 'discontinued' },] }, { name: 'Parent Brand 2', childBrands: [{ name: 'Child Brand 1', status: 'discontinued' }, { name: 'Child Brand 2', status: 'active' },] }];
    
    const filtered = array.map(parent => ({
      ...parent,
      childBrands: parent.childBrands.filter(child => child.status === 'active')
    }));
    
    console.log(filtered)