检查对象是否可在JavaScript中序列化的可靠方法 [英] Reliable way to check if objects is serializable in JavaScript
问题描述
是否存在已知的方法或库,该库已经具有用于评估对象是否可在JavaScript中进行序列化的助手?
Is there a known way or a library that already has a helper for assessing whether an object is serializable in JavaScript?
我尝试了以下操作,但是它不涵盖原型属性,因此提供了误报:
I tried the following but it doesn't cover prototype properties so it provides false positives:
_.isEqual(obj, JSON.parse(JSON.stringify(obj))
还有另一个lodash函数,可以使我更接近真相,_.isPlainObject
.但是,虽然_.isPlainObject(new MyClass())
返回false
,但是_.isPlainObject({x: new MyClass()})
返回true
,因此需要递归应用.
There's another lodash function that might get me closer to the truth, _.isPlainObject
. However, while _.isPlainObject(new MyClass())
returns false
, _.isPlainObject({x: new MyClass()})
returns true
, so it needs to be applied recursively.
在我自己冒险之前,是否有人知道一种已经可靠的方法来检查JSON.parse(JSON.stringify(obj))
是否实际上会导致与obj
相同的对象?
Before I venture by myself on this, does anybody know an already reliable way for checking if JSON.parse(JSON.stringify(obj))
will actually result in the same object as obj
?
推荐答案
最后,我创建了自己的利用Underscore/Lodash的_.isPlainObject
的方法.我的功能最终类似于@bardzusny提出的功能,但是我也发布了我的函数,因为我更喜欢简单性/明晰性.随时概述优点/缺点.
In the end I created my own method that leverages Underscore/Lodash's _.isPlainObject
. My function ended up similar to what @bardzusny proposed, but I'm posting mine as well since I prefer the simplicity/clarity. Feel free to outline pros/cons.
var _ = require('lodash');
exports.isSerializable = function(obj) {
if (_.isUndefined(obj) ||
_.isNull(obj) ||
_.isBoolean(obj) ||
_.isNumber(obj) ||
_.isString(obj)) {
return true;
}
if (!_.isPlainObject(obj) &&
!_.isArray(obj)) {
return false;
}
for (var key in obj) {
if (!exports.isSerializable(obj[key])) {
return false;
}
}
return true;
};
这篇关于检查对象是否可在JavaScript中序列化的可靠方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!