Home > Back-end >  Keep parent object while filtering on deeply nested array within the object
Keep parent object while filtering on deeply nested array within the object

Time:07-25

I've searched SO for a solution to this but having a hard time applying any solutions given. I'm using JavaScript/React so I need a solution in JS.

An object is returned from a data base with the following structure,

source.source.source (three levels, all children are called source).

The first source is an object, the second source is also an object and the third source is an array with all the elements.

Each element in the array has a property, "isActive", as in

source.source.source.isActive

I thought the below code would keep the entire object but it loses the two parent nodes and all that data (source, and source) and only returns the array nested within source.source. I need the entire returned object from axios filtered.

const responseDataFiltered = source.source.source.filter(obj => Boolean(obj.isActive) === true)

I need a way to keep all parent elements while only showing the array elements that have isActive === true.

What I am trying to achieve is to filter a response from a database where the returned elements have the property isActive set to true, and I need the main structure/parent elements. So essentially, I need a copy of the main parent element source with it's nested data but filter out all isActive === false.

I am getting the data using Axios from an api. The response is the entire object that has the deeply nested array with the thousands of elements I need to filter on isActive. Once the returned object has filtered out all the isActive === false I want to pass it to a useState hook and display the data.

CodePudding user response:

You can just replace the nested array with the filter data:

const source = {
    one: 1,
    two: 2,
    source:{
        three: 3,
        four: 4,
        source: [
            {isActive: true},
            {isActive: true},
            {isActive: false},
            {isActive: false},
        ],
    },
};

const actives = source.source.source.filter(({ isActive }) => isActive);
const responseDataFiltered = {
  ...source, 
  source: {
    ...source.source, 
    source: actives,
  },
};

console.log(responseDataFiltered);
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related