如何删除嵌套属性?

Rai*_*ner 5 javascript jquery

我有这个 JSON 文件:http : //danish-regional-data.googlecode.com/svn/trunk/danish_regional_data.json

如何删除所有attribues within_5_kmwithin_10_kmwithin_25_kmwithin_50_kmwithin_100_km所有的邮政编码?

我已阅读此问题:删除 JSON 属性

$(document).ready(function() {

    $.getJSON("post.json", function(data) {

    var pc = data.postalcodes;
    for (var id in pc) {
       if(pc.hasOwnProperty(id)) {
          for(var attr in pc[id]) {
             if(pc[id].hasOwnProperty(attr) && attr.indexOf('within_') === 0) {
               delete pc[id][attr];
             }
          }
       }
    }

    $("#json").html(pc);

    });

});
Run Code Online (Sandbox Code Playgroud)

pro*_*son 2

转到您提供的 json url 并打开 Firebug 控制台。然后放入以下代码并执行它:

var p = document.getElementsByTagName('pre');
for(i=0; i < p.length; i++) {

  var data = JSON.parse(p[i].innerHTML);
  var pc = data.postalcodes;

  // this is the code i gave you... the previous is jsut to pull it out of the page
  // in Firebug - this works for me

  for (var id in pc) {
     if(pc.hasOwnProperty(id)) {
        for(var attr in pc[id]) {
          if(pc[id].hasOwnProperty(attr) && attr.indexOf('within_') === 0) {
             console.log('Deleting postalcodes.'+id+'.'+attr);
             delete pc[id][attr];
           }
        }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)
// assume data is the complete json

var pc = data.postalcodes;
for (var id in pc) {
   if(pc.hasOwnProperty(id)) {
      for(var attr in pc[id]) {
         if(pc[id].hasOwnProperty(attr) && attr.indexOf('within_') === 0) {
           delete pc[id][attr];
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)