Javascript本地/优雅方式从对象中剥离属性

时间:2013-09-06 12:53:58

标签: javascript

我想知道是否有原生/优雅的方式来做到这一点:

var object = {
    value: 1,
    desc: 'an object',
    method: function(){
        return this.description + ' with value: ' + this.value;
    },
};
var onlyProperties = JSON.parse(JSON.stringify(object));

正如您所看到的,我只想要没有任何方法的属性。上面的代码有效,但这样做是错误的。

4 个答案:

答案 0 :(得分:2)

如果您不是在寻找递归解决方案,这是一种简单的方法。

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];
    }
}

答案 1 :(得分:1)

原生方式是这样的:

var foo = {
    /* stuff*/
};

var onlyProperties = {};

for (var bar in foo) {
    if (typeof foo[bar] != "function") {
        onlyProperties[bar] = foo[bar];
    }
}

这样就可以保留原始对象和仅包含非功能成员的新对象。

答案 2 :(得分:0)

然后返回函数调用呢?

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);
});

您可以使用replacer参数更好地控制序列化的内容。

答案 3 :(得分:0)

for (var p in object) {
  if (object.hasOwnProperty(p)) {
    if (typeof object[p] === 'function') delete object[p];
  }
}