gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:44:14 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com