Remove Property dynamically from JSON Object

377 Views Asked by At

I have to remove properties from a JSON object. It's like I need to write a framework where I pass an array of location from where the fields needs to be redacted. My JSON request looks like this

{
"name": "Rohit",
"other": [{
    "tfn": "2879872934"
}, {
    "tfn": "3545345345"
}],
"other1": {
    "tfn": "3545345345"
},
"other2": {
    "other3": [{
        "tf2n": "2879872934"
    }, {
        "tfn": "3545345345"
    }, {
        "tfn": "2342342234"
    }]
},
"card": "sdlkjl",
"tfn": "2879872934",
"f": true}

As I said above, this is how I captured the locations that needs to removed

let paths = ['other.tfn','tfn','other1.tfn','other2.other3.tfn'];

It remove tfn fields from almost all the places and returns

{
"name": "Rohit",
"other": [
    {},
    {}
],
"other1": {},
"other2": {
    "other3": [
        {
            "tf2n": "2879872934"
        },
        {},
        {}
    ]
},
"card": "sdlkjl",
"f": true}

I am curious if someone can suggest a better way to write below code

paths.forEach(function (path) {
           let keys = path.split('.');
           deepObjectRemove(jsonObject, keys);
        });

method

var deepObjectRemove = function(obj, path_to_key){
if(path_to_key.length === 1){
    delete obj[path_to_key[0]];
    return true;
}else{
    if(obj[path_to_key[0]] && Array.isArray(obj[path_to_key[0]])) {
        obj[path_to_key[0]].forEach(function (value) {
            deepObjectRemove(value, path_to_key.slice(1));
        });
        //return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
    }else if(obj[path_to_key[0]]){
        deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
    }else{
        return false;
    }
}};
1

There are 1 best solutions below

0
On

function deepObjectRemove(object, path) {
 const parts = path.split(".");
 let current;
 while (current = parts.shift()) {
  if (!object) {
   return;
  }
  const item = object[current];
  if (item !== undefined) {
   if (!parts.length) {
    delete object[current];
   }
   if (item instanceof Array) {
    return item.forEach((item) => deepObjectRemove(item, parts.join(".")));
   }
  }
  object = item;
 }
}

const object = {
 a: {
  b: {
   c: "1",
   d: 0
  }
 },
 b: [
  {
   a: {
    b: "0",
    c: "1"
   }
  },
  {
   a: {
    b: "0",
    c: "1"
   }
  }
 ]
};
console.log("before", object);
[
 "a.b.c",
 "b.a.c"
].forEach((path) => deepObjectRemove(object, path));
console.log("after", object);