Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to recursively delete a field from an object in javascript ignoring optional fields

I have a an Object and I need to delete all the "id" attributes inside at every deep level except for some of them.

I did this function:

const removeFieldFromObject = ({ obj, fieldName, ignoreFields = [] }) => {
  if (typeof obj !== "object" || obj === null) {
    return obj;
  }

  if (Array.isArray(obj)) {
    for (var i = 0; i < obj.length; i++) {
      obj[i] = removeFieldFromObject({ obj: obj[i], fieldName, ignoreFields });
    }
  } else {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        if (prop === fieldName && !ignoreFields.includes(obj[prop])) {
          delete obj[prop];
        } else {
          obj[prop] = removeFieldFromObject({
            obj: obj[prop],
            fieldName,
            ignoreFields,
          });
        }
      }
    }
  }
  return obj;
};

If i invoke it with this object in the following way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const obj = {
  id:1,
  data:{
    id:2,
    cards:{
      id:123,
      name:"my name",
      document:{
        id:2,
        url:"my url"
      }
    }
  }
}

const formattedObj = removeFieldFromObject({obj, fieldName: "id", ignoreFields: ["document"]})

It deletes the "id" attribute at all levels

I want it do remove all the attributes "id" except for document objects. This method removes them at every level. The reason is the condition on ignoreFields that is always true when it goes inside the document object and it checks the actual props. I looked around and found many similar questions but not with optional attributes.

Do you have any suggestion? I accept also solutions with lodash or similar.

>Solution :

if (prop === fieldName && !ignoreFields.includes(obj[prop])) {
  delete obj[prop];
} else {
  obj[prop] = removeFieldFromObject(…);
}

This doesn’t make a lot of sense – or at least, it doesn’t match how you are calling the function. It checks for the value of the property to delete in the ignoreFields. What you actually want is to check the property name before doing the recursive call, so that nothing in .document does get visited:

if (prop === fieldName) {
  delete obj[prop];
} else if (!ignoreFields.includes(prop)) {
  obj[prop] = removeFieldFromObject(…);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading