I have a JSON in javascript. That contains such values as {id:""}. I need to drop those kind of values from the JSON object. Is there a simple way to do it?
2 Answers
A Json object is tree-like. You can use such a recursive function to walk and clean it:
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);
}
}
}
}
How to use the above code within the 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);
Result:
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
}
1 Comment
You can use the delete command.
delete obj.id;
From the documentation:
delete
The delete operator removes a property from an object.
What you would want to do is iterate over all the objects in your JSON and when you detect an empty id attribute obj.id == "", you'll execute the delete command.
If you have multiple properties that you want to delete, you'll have to iterate over each one and test it against an empty string. If you are not sure how many attributes you'll want to remove then you'll simply have to iterate over each attribute for each object.
for..inandhasOwnPropertyif(obj.id.length !== 0){}.