javascript - 如何删除 ""(空字符串)的 JSON 元素?

标签 javascript

我在 javascript 中有一个 JSON。其中包含诸如 {id:""} 之类的值。我需要从 JSON 对象中删除这些类型的值。有简单的方法吗?

最佳答案

Json 对象是树状的。您可以使用这样的递归函数来遍历和清理它:

function walkclean(x) {
  var type = typeof x;
  if (x instanceof Array) {
    type = 'array';
  }
  if ((type == 'array') || (type == 'object')) {
    for (k in x) {
      var v = x[k];
      if ((v === '') && (type == 'object')) {
        delete x[k];
      } else {
        walkclean(v);
      }
    }
  }
}

如何在 MongoDB shell 中使用上述代码:

var test = {
  a: "foo",
  b: [ "hi", "you", "", "ouch", "", "again!"],
  c: [ { nasty: "me", hit: "", whatever: [ "yeah" ] }, 
       { ha: { my: "", oh: "yeah", foo: ""}} ],
  d: "",
  e: 42
};

printjson(test);
walkclean(test);

print('=>');
printjson(test);

结果:

snippets/walkclean$ mongo walkclean.js
MongoDB shell version: 2.4.10
connecting to: test
{
    "a" : "foo",
    "b" : [
            "hi",
            "you",
            "",
            "ouch",
            "",
            "again!"
    ],
    "c" : [
            {
                    "nasty" : "me",
                    "hit" : "",
                    "whatever" : [
                            "yeah"
                    ]
            },
            {
                    "ha" : {
                            "my" : "",
                            "oh" : "yeah",
                            "foo" : ""
                    }
            }
    ],
    "d" : "",
    "e" : 42
}

=>

{
    "a" : "foo",
    "b" : [
            "hi",
            "you",
            "",
            "ouch",
            "",
            "again!"
    ],
    "c" : [
            {
                    "nasty" : "me",
                    "whatever" : [
                            "yeah"
                    ]
            },
            {
                    "ha" : {
                            "oh" : "yeah"
                    }
            }
    ],
    "e" : 42
}

关于javascript - 如何删除 ""(空字符串)的 JSON 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339813/

相关文章:

javascript - 如何在 jQuery 中将 .done 或 .complete 与 .toggle 一起使用

javascript - Sencha 触摸 : How to programmatically focus on a textfield on ios?

javascript - 当只选择一个元素时,为什么我的 if 语句返回大于 1 的值?

javascript - 如何检测 iPhone X (Ionic - cordova app)

javascript - 我无法让这个回调工作

javascript - 我们构建时刻时区的方式有什么区别?

javascript - Google Calendar API - 不再授权读取?

javascript - 单击后更改按钮链接

javascript - 从外部更改 Phaser 状态

c# - 将重点放在自定义验证器上