Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert an object which can be array or single object to an array in javascript

I have an object like below

const foo = (x : Array<string> | string) {
   ...
}

Now I want to treat x always as an array, I have done this

const y = Array.isArray(x) ? x : [x];

I know I can have another function to do this, looking for some built-in javascript function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(this is simplified version I am doing this multiple times try to DRY)

>Solution :

You can use [].concat() or wrap the item with an array, and then flatten it:

const fn1 = x => [].concat(x)

console.log(fn1({ a: 1 }))
console.log(fn1([{ a: 1 }]))

const fn2 = x => [x].flat()

console.log(fn2({ b: 2 }))
console.log(fn2([{ b: 2 }]))

If the function only has a single parameter, you can use rest params, and flatten the array of arguments:

const fn = (...x) => x.flat()

console.log(fn({ a: 1 }))
console.log(fn([{ a: 1 }]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading