Home > Software engineering >  How do i perform an operation on a child element and return the parent?
How do i perform an operation on a child element and return the parent?

Time:06-18

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" }

CodePudding user response:

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)

CodePudding user response:

You use Array#map on the major array and Array#filter on the minor arrays as follows:

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' }, ] } ],

      output = array.map(
          ({childBrands,...rest}) =>
          ({
              ...rest,
              childBrands:childBrands.filter(
                  ({status}) => status === 'active'
              )
          })
      );
      
console.log( output );

  • Related