Rails beginner Rails beginner - 7 months ago 20
Javascript Question

How to remove nested attributes?

I have this JSON file: http://danish-regional-data.googlecode.com/svn/trunk/danish_regional_data.json

How do I remove all the attribues

within_5_km
,
within_10_km
,
within_25_km
,
within_50_km
,
within_100_km
for all postcodes?

I have read this question: Remove a JSON attribute

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

});

});

Answer

Go to the json url you provided and open the Firebug console. Then drop in the folloing code and execute it:

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];
           }
        }
     }
  }
}

// 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];
         }
      }
   }
}