我在 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/