Skip to content
Advertisement

How to remove extra unknown properties from object in javascript

I was just wondering is it possible to remove extra unknown properties from object.

The exact problem which I am facing is that I know what fields I need in object, but I don’t know what extra is coming and I need to remove those extras.

One option which comes in my mind is using hasOwnProperty function since we know what all properties we need.

Ex : Suppose we are getting below object :

{
    name: "Harry",
    age: 16,
    gender: "Male",
    Address: {
       prop1: "Hello",
       City: "LA"
    }
}

Now, we know that we need name, age, address and city in address beforehand but we are getting prop1 also as extra here and we don’t know that it is exactly. It could be anything. We need to remove this prop1 from this object. This is just an example.

I think we need to use some recursive approach because the extra property could be at any place in the object.

Note: We have a list of properties which we need in advance.

Advertisement

Answer

I defined a schema form of json (modify it as you want) and then I made a function that receives the json required to delete unwanted elements from it.

const needAttribute =  {
 name: "Harry",
 age: 16,
 gender: "Male",
 Address: {
   City: "LA"
}
}

var json =
{
 name: "Harry",
 age: 16,
 gender: "Male",
 Address: {
   prop1: "Hello",
   City: "LA"
}
}
function getNeedAttributeFromJson(Myjson){
  for(var element in Myjson){
    if(needAttribute.hasOwnProperty(element)){
      if (typeof Myjson[element] === "object") {
        for(var subElement in Myjson[element]){
          if(!needAttribute[element].hasOwnProperty(subElement)){
            delete Myjson[element][subElement];
          }
        }
      }else{
        continue;
      }
    }else{
       delete Myjson[element];
    }
  }

  return Myjson;
}
console.log(getNeedAttributeFromJson(json));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement