3

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?

1
  • 2
    use constructor method. Commented May 28, 2019 at 9:25

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

@raina77ow Yeah, although if only Object and Array are considered it doesn't matter
Thanks - yes - not sure why I used new there!
@match Consider accepting the answer if you are satisfied with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.