Copy properties but not function properties, using spread operator or similar

350 Views Asked by At

Is there a way in JS to copy all non-function properties using the spread operator or the like? this won't do it obviously (since it will copy function references):

  getSerializableData(): Partial<this> {
    return {
      ...this,
      subscribers: undefined,
      subscribersByEvent: undefined,
      
    }
  }

in pseudo-code it would be like:

  getSerializableData(): Partial<this> {
    return {
      ...Object.serializableFields(this),   // <<< here
      subscribers: undefined,
      subscribersByEvent: undefined,
    }
  }

so the spread operator would only act on non-functions properties, etc. Is this possible?

1

There are 1 best solutions below

2
Steven Spungin On

You can filter the entries by value type, and then use a reduce function to zip the object back up.

const filteredObject = Object.entries(this)
  .filter(it => typeof(it[1] !== 'function'))
  .reduce( (acc,item) => { acc[item[0]]=item[1]; return acc }, {} )

As Bergi suggested, you can zip up your object using Object.fromEntries.

const entries = Object.entries(this)
  .filter(it => typeof(it[1] !== 'function'))

const filteredObject = Object.fromEntries(entries)