Javascript本机/优雅的从对象中剥离属性的方法
我想知道是否有一种本地/优雅的方法可以做到这一点:Javascript本机/优雅的从对象中剥离属性的方法,javascript,Javascript,我想知道是否有一种本地/优雅的方法可以做到这一点: var object = { value: 1, desc: 'an object', method: function(){ return this.description + ' with value: ' + this.value; }, }; var onlyProperties = JSON.parse(JSON.stringify(object)); 正如你所看到的,我只需要属性,而
var object = {
value: 1,
desc: 'an object',
method: function(){
return this.description + ' with value: ' + this.value;
},
};
var onlyProperties = JSON.parse(JSON.stringify(object));
正如你所看到的,我只需要属性,而不需要任何方法。上面的代码可以工作,但这样做感觉不对。如果您不是在寻找递归解决方案,这里有一个简单的方法
for (var i in obj) {
if (obj.hasOwnProperty(i) && typeof obj[i] === 'function') {
delete obj[i];
}
}
如果您想要不带功能的副本:
var copy = {};
for (var i in obj) {
if (obj.hasOwnProperty(i) && typeof obj[i] !== 'function') {
copy[i] = obj[i];
}
}
那么这个函数返回函数调用呢
var obj = {
value: 1,
desc: 'an object',
method: function(){ return this.desc + ' with value ' + this.value; }
};
console.log(JSON.stringify(obj)); // "{"value":1,"desc":"an object"}"
如果删除方法调用是您的目标,JSON.stringify
应该可以。如果确实需要粒度:
JSOS.stringify(obj, function(k,v){
// testing for `typeof x === 'function' really won't get hit,
// but this does give you an example of how to proceed.
return (typeof v === 'function' ? undefined : v);
});
您可以使用参数对序列化内容进行更多控制。本机方式如下:
for (var p in object) {
if (object.hasOwnProperty(p)) {
if (typeof object[p] === 'function') delete object[p];
}
}
var foo = {
/* stuff*/
};
var onlyProperties = {};
for (var bar in foo) {
if (typeof foo[bar] != "function") {
onlyProperties[bar] = foo[bar];
}
}
通过这种方式,您可以保留原始对象和新对象,其中只包含其非函数成员。我更喜欢您的解决方案+1.谢谢!我很感动:)我经常忽略和使用js中的delete关键字。另外,我想为未来的读者补充一点: