js 去除JSON里的值为空字符串的键

如题,假设obj = {'a': 1, 'b': '', 'c': ['', 1, {'a': ''}], 'd': {'a': {'b': '', 'c': {'d': ''}}}}

那么结果应为{ 'a': 1, 'c': [ '', 1, { a: '' } ], 'd': { 'a': { 'c': {} } } }

方案一:for in

function remove_empty(obj) {
  for (let k in obj) {
    v = obj[k];
    if (v === '') delete obj[k];
    else if (v.constructor == Object) remove_empty(v);
  }
}

方案二:forEach

function remove_empty(obj) {
  Object.keys(obj).forEach(function(k) {
    v = obj[k];
    if (v === '') delete obj[k];
    else if (v.constructor == Object) remove_empty(v);
  })
}

方案三:采用while来替代递归

function remove_empty(obj) {
  let objects = [obj];
  do {
    let sub_objects = [];
    objects.forEach(function(i) {
      Object.keys(i).forEach(function(k) {
        if (i[k] === '') delete i[k];
        else if (i[k].constructor == Object) sub_objects.push(i[k]);
      });
    });
    objects = sub_objects;
  } while (objects != false);
}

附:Python版remove_empty

def remove_empty(obj: dict) -> None:
    for k, v in list(obj.items()):
        if v == '':
            del obj[k]
        elif isinstance(v, dict):
            remove_empty(v)
上一篇:玩转PowerShell第一节——【后台任务处理】-技术&分享


下一篇:Java集合一