-1

If I have a JSON input like the below:

{
  "a": [],
  "b" : "cat",
  "c" : "10001",
  "g" : "",
  "h" : {
      "d": {},
      "m": []
  }   
}

How could I write a function that would remove all rows where the value is brackets: {} or [], resulting in:

{
  "b" : "cat",
  "c" : "10001",
  "g" : ""
}
Nerl
  • 41
  • 7

2 Answers2

2

function clean(obj) {
  for(var key in obj) {
    if(obj[key] instanceof Array && ! obj[key].length) // if it's an array and it's empty
      delete obj[key];                                 // then remove it
    else if(typeof obj[key] === "object") {            // if it's an object
      clean(obj[key]);                                 // clean it
      if(! Object.keys(obj[key]).length)               // and if after cleaning it turned out to be empty
        delete obj[key];                               // then remove it
    }
  }
}

var obj = {
  "a": [],
  "b" : "cat",
  "c" : "10001",
  "d" : [55, 80],
  "g" : "",
  "h" : {
      "d": {},
      "m": []
  },
  "i" : {
      "d": {
        "l": 0
      },
      "m": []
  }   
};

clean(obj);
console.log(obj);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

You can use this function to iterate through the properties of your object and only grab the values that are not of the type "object". Note the function also checks hasOwnProperty to ensure that it's not an object's prototype property

var strippedObject;
for (var property in object) {
    if (object.hasOwnProperty(property)) {
        if(typeof object[property] != "object"){
            strippedObject[property] = object[property];
        }
    }
}
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69