I receive a data value from a API, and I want to make a condition to deal with it. Sometimes it can comes as an array or object. I will use a simple example.
data = [1,2,3] // These values come from API
data.map(i => i++)
The problem is: Sometimes data can also comes as this
data = {
arr: [1,2,3]
}
// It evals an error in .map, because now "data" is an object
I know that I can solve it making something like this:
if(Array.isArray(data))
data.map(i => i++);
else
data.arr.map(i => i++);
But my code is not just a one line .map. Is there a way to make this simple condition without copying and paste code?
Thanks!
function getData( data ) { return Array.isArray( data ) ? data : data.arr }and then use that everywheregetData( data ).map( i => i++ )