如何遍历对象的所有属性并删除特定属性AngularJS

时间:2017-12-05 22:51:41

标签: javascript angularjs json loops

我有一个类似以下的JavaScript对象:

{
    "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": {}
            }
        }
    }
}

现在我想迭代对象并删除所有"test"属性。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

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);