d23
d23

Reputation: 63

Javascript native/elegant way to strip properties from object

I would like to know if there is a native/elegant way to do this:

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

As you can see I just want the properties without any methods in it. The above code works but it feels wrong to do it this way.

Upvotes: 1

Views: 1031

Answers (4)

Brad Christie
Brad Christie

Reputation: 101614

and what about this returns function calls?

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"}"

If removing the method calls is your aim, JSON.stringify should be fine as-is. If you really want granularity:

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

You can use the replacer parameter to have more control over what's serialized.

Upvotes: 0

Joon
Joon

Reputation: 9914

If you are not looking for a recursive solution, here's a simple way to do it.

for (var i in obj) {
    if (obj.hasOwnProperty(i) && typeof obj[i] === 'function') {
        delete obj[i];
    }
}

If you want a copy without functions:

var copy = {};
for (var i in obj) {
    if (obj.hasOwnProperty(i) && typeof obj[i] !== 'function') {
        copy[i] = obj[i];
    }
}

Upvotes: 2

Geeky Guy
Geeky Guy

Reputation: 9379

The native way is something like this:

var foo = {
    /* stuff*/
};

var onlyProperties = {};

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

This way you keep both the original object and the new one containing only its non-function members.

Upvotes: 1

Andy
Andy

Reputation: 63570

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

Upvotes: 0

Related Questions