Node.js – 从JSON对象中删除空元素

我试图从JSON对象中删除空/空元素,类似于python webutil / util.py – > trim_nulls方法的function。 是否有内置的节点,我可以使用,或者是一个自定义的方法。

例:

var foo = {a: "val", b: null, c: { a: "child val", b: "sample", c: {}, d: 123 } }; 

预期结果:

 foo = {a: "val", c: { a: "child val", b: "sample", d: 123 } }; 

我不知道为什么人们提出我原来的答案,这是错误的(猜测他们看起来太快,就像我做的那样)。 无论如何,我不熟悉节点,所以我不知道它是否包含这个东西,但我想你会需要这样的东西,直接JS:

 var remove_empty = function ( target ) { Object.keys( target ).map( function ( key ) { if ( target[ key ] instanceof Object ) { if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') { delete target[ key ]; } else { remove_empty( target[ key ] ); } } else if ( target[ key ] === null ) { delete target[ key ]; } } ); return target; }; remove_empty( foo ); 

我没有在foo尝试使用这个数组 – 可能需要额外的逻辑来处理这个问题。

感谢所有的帮助..我已经拼凑了下面的代码,使用反馈的所有与foo一起工作的评论。

 function trim_nulls(data) { var y; for (var x in data) { y = data[x]; if (y==="null" || y===null || y==="" || typeof y === "undefined" || (y instanceof Object && Object.keys(y).length == 0)) { delete data[x]; } if (y instanceof Object) y = trim_nulls(y); } return data; } 

你可以用一个for循环过滤并输出到一个新的干净的对象:

 var cleanFoo = {}; for (var i in foo) { if (foo[i] !== null) { cleanFoo[i] = foo[i]; } } 

如果您还需要处理子对象,则需要recursion。

我发现这是最优雅的方式。 我也相信JS引擎对它进行了大量的优化。

使用内置的JSON.stringify(value[, replacer[, space]])function。 文档在这里 。

例子是在从外部API中检索一些数据的情况下,相应地定义一些模型,得到结果和所有无法定义或不需要的结果:

 function chop (obj, cb) { const valueBlacklist = ['']; const keyBlacklist = ['_id', '__v']; let res = JSON.stringify(obj, function chopChop (key, value) { if (keyBlacklist.indexOf(key) > -1) { return undefined; } // this here checks against the array, but also for undefined // and empty array as value if (value === null || value === undefined || value.length < 0 || valueBlacklist.indexOf(value) > -1) { return undefined; } return value; }) return cb(res); } 

在你的实现。

 // within your route handling you get the raw object `result` chop(user, function (result) { var body = result || ''; res.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'application/json' }); res.write(body); // bang! finsihed. return res.end(); }); // end of route handling