javascript Node.js - 从 JSON 对象中删除空元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11874724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js - Remove null elements from JSON object
提问by Steve Davis
I am trying to remove null/empty elements from JSON objects, similar to the functionality of the python webutil/util.py -> trim_nulls method. Is there something built in to Node that I can use, or is it a custom method.
我正在尝试从 JSON 对象中删除空/空元素,类似于 python webutil/util.py -> trim_nulls 方法的功能。是否有我可以使用的内置于 Node 的东西,或者它是一种自定义方法。
Example:
例子:
var foo = {a: "val", b: null, c: { a: "child val", b: "sample", c: {}, d: 123 } };
Expected Result:
预期结果:
foo = {a: "val", c: { a: "child val", b: "sample", d: 123 } };
回答by JMM
I don't know why people were upvoting my original answer, it was wrong (guess they just looked too quick, like I did). Anyway, I'm not familiar with node, so I don't know if it includes something for this, but I think you'd need something like this to do it in straight JS:
我不知道为什么人们对我的原始答案投赞成票,这是错误的(猜想他们只是看起来太快了,就像我一样)。无论如何,我不熟悉 node,所以我不知道它是否包含一些东西,但我认为你需要这样的东西才能在直接的 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 );
I didn't try this with an array in foo
-- might need extra logic to handle that differently.
我没有在数组中尝试过这个foo
——可能需要额外的逻辑来以不同的方式处理它。
回答by Durmu?
You can use like this :
你可以这样使用:
Object.keys(foo).forEach(index => (!foo[index] && foo[index] !== undefined) && delete foo[index]);
回答by Steve Davis
Thanks for all the help.. I've pieced the following code using the feedback in all of the comments which works with 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;
}
回答by eljefedelrodeodeljefe
I found this to be the most elegant way. Also I believe JS-engines are heavily optimized for it.
我发现这是最优雅的方式。我也相信 JS 引擎已经针对它进行了大量优化。
use built in
JSON.stringify(value[, replacer[, space]])
functionality. Docs are here.
使用内置
JSON.stringify(value[, replacer[, space]])
功能。文档在这里。
Example is in context of retrieving some data from an external API, defining some model accordingly, get the result and chop of everything that couldn't be defined or unwanted:
示例是在从外部 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);
}
In your implementation.
在您的实施中。
// 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
回答by elclanrs
You can just filter with a for
loop and output to a new clean object:
您可以使用for
循环过滤并输出到新的干净对象:
var cleanFoo = {};
for (var i in foo) {
if (foo[i] !== null) {
cleanFoo[i] = foo[i];
}
}
If you need to process children objects too you'll need recursion.
如果您也需要处理子对象,则需要递归。