Spread a class instance

Viewed 137

Is there a way to spread a class instance? I have been trying to but I keep getting an empty object returned.
What I've tried:

const ctx = new AudioContext()
const example = {...ctx}


//prints {}
console.log(example)

I've also tried using Object.assign and encountered the same thing. What am I missing here?

Something to note: It works on custom classes.

1 Answers

You can use a simple for...in loop for this purpose.

const ctx = new AudioContext();
const toObject = o => {
  const res = {};//or Object.create(null)
  for(const key in o) res[key] = o[key];
  return res;
};
console.log(toObject(ctx));

Related