match
match

Reputation: 11060

Create an empty object/array, based on an existing object/array

I'm writing a function that takes as an argument either an object or an array, and I want to create a new, empty copy of it and populate it with transformed data from the original object.

I'm wondering if there's a way to make this new object/array simply, without having to test what type the thing is and act appropriately.

The 'long' way is currently to do:

const transf = (thing) => {
  if (typeof(thing) === 'array') {
    const new = []
  }  else {
    const new = {}
  }
}

I'm hoping there's a nice 'builtin' way I can do something like:

const transf = (thing) => {
  const new = thing.emptyCopy()
}

I've looked at Object.create but that always makes an object (even if the prototype is an array), and typeof returns a string, which can't be used with e.g. new etc.

Is there a shorthand way to do this, or am I out of luck?

Upvotes: 3

Views: 260

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

You can use constructor property of thing. And don't use new as variable name.

const transf = (thing) => {
  const newelm = new thing.constructor()
}

Demo:

const transf = (thing) => {
  return new thing.constructor()
}

console.log(transf(['arra']))
console.log(transf({key:'value'}))

Upvotes: 8

Related Questions