Med
Med

Reputation: 117

How to Iterate through all property of object and delete specific property AngularJS

I have a JavaScript object like the following:

{
    "widget": {
        "debug": "on",
        "test": {},
        "window": [{
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500,
            "test": {}
        }]
        "image": {
            "src": "Images/Sun.png",
            "name": "sun1",
            "test": {},
            "vOffset": 250
        },
        "text": {
            "data": "Click Here",
            "test": {},
            "alignment": "center",
            "image": {
                "src": "Images/test.png",
                "name": "sun2",
                "test": {}
            }
        }
    }
}

Now I want to Iterate through the object and delete all "test" property. How can I do that?

Upvotes: 0

Views: 50

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13488

var data = {
  "widget": {
    "debug": "on",
    "test": {},
    "window": [{
      "title": "Sample Konfabulator Widget",
      "name": "main_window",
      "width": 500,
      "height": 500,
      "test": {}
    }],
    "image": {
      "src": "Images/Sun.png",
      "name": "sun1",
      "test": {},
      "vOffset": 250
    },
    "text": {
      "data": "Click Here",
      "test": {},
      "alignment": "center",
      "image": {
        "src": "Images/test.png",
        "name": "sun2",
        "test": {}
      }
    }
  }
};

function DeleteProperty(input, name) {
  if (input instanceof Object) {
    for (var prop in input) {
      if (prop == name)
        delete input[prop]
      else
        DeleteProperty(input[prop], name)
    }
  }
}

DeleteProperty(data, 'test');
console.log(data);

Upvotes: 4

Related Questions