Home > database >  How i can filter only true value from object and maintain the object structure
How i can filter only true value from object and maintain the object structure

Time:12-31

This is my current object which i get but i want to filter out only true values and also maintain the same structure in return.

Current Object =

errors :{
    frontdesk: {
      PreAudit: true,
      AuthSent: false,
      Limitation: false,
    },

    clinical: {
      medicaid: true,
      Vitals: true,
      Height: false,
    },
    eligibilityVerification: {
      Mentioned: true,
      EVAttached: false,
    }
  }
i want like this =

errors :{ frontdesk: { PreAudit: true, },

clinical: {
  medicaid: true,
  Vitals: true,
},
eligibilityVerification: {
  Mentioned: true,
}

}

CodePudding user response:

You can convert your Object into an array, and then you can use .filter.

const myArray = errors.entries(obj);
const filtered = myArray.filter (([key, value]) => value === true);
const backToObject = Object.fromEntries(filtered);

CodePudding user response:

To filter out only the true values in the object, you can use the Object.entries()

const filteredErrors = Object.entries(errors)
  .filter(([key, value]) => value)
  .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});

This will return a new object with the same structure as the original errors object, but with only the true values.

  • Related