toArray
Paquete: @tiendana/utils
Convierte cualquier valor a array. Si el valor ya es un array, lo retorna sin cambios. Útil para normalizar inputs que pueden ser string o array.
Características
✅ Normaliza inputs variables
✅ Maneja cualquier tipo de dato
✅ No modifica arrays existentes
✅ Simple y directo
Firma
function toArray(value: any): string[]
Parámetros
| Parámetro | Tipo | Descripción | Requerido |
|---|---|---|---|
value | any | Valor a convertir a array | ✅ |
Retorno
Tipo: string[]
- Si
valuees array: retorna el mismo array - Si
valueno es array: retorna[value]
Ejemplos de Uso
Normalización Básica
import { toArray } from '@tiendana/utils';
toArray('hello'); // ['hello']
toArray(['a', 'b']); // ['a', 'b']
toArray(123); // [123]
toArray(null); // [null]
toArray(undefined); // [undefined]
toArray({ id: 1 }); // [{ id: 1 }]
Con Parámetros de Query
// URL: /products?category=electronics
// o URL: /products?category=electronics&category=toys
function getCategories(query: URLSearchParams) {
const category = query.get('category');
// category puede ser string o null
const categories = toArray(category || []);
return categories.filter(c => c !== null);
}
Con Datos de API Variables
interface ApiResponse {
// Puede ser string único o array
tags: string | string[];
}
function processTags(response: ApiResponse) {
// Normalizar a array siempre
const tagsArray = toArray(response.tags);
tagsArray.forEach(tag => {
console.log(`Processing tag: ${tag}`);
});
}
processTags({ tags: 'javascript' });
// Processing tag: javascript
processTags({ tags: ['javascript', 'react'] });
// Processing tag: javascript
// Processing tag: react
En Funciones Utilitarias
function processItems(items: string | string[]) {
const itemsArray = toArray(items);
return itemsArray.map(item => ({
id: generateId(),
name: item,
timestamp: Date.now()
}));
}
processItems('Single Item');
// [{ id: '...', name: 'Single Item', ... }]
processItems(['Item 1', 'Item 2']);
// [{ id: '...', name: 'Item 1', ... }, { id: '...', name: 'Item 2', ... }]
Con Form Data
function handleFormSubmit(formData: FormData) {
// FormData.get() retorna string | File | null
const categories = formData.get('categories');
// Normalizar para procesamiento
const categoriesArray = toArray(categories);
return {
...otherFields,
categories: categoriesArray.filter(Boolean)
};
}
En Procesamiento de Archivos
interface UploadConfig {
files: File | File[];
}
function uploadFiles(config: UploadConfig) {
const filesArray = toArray(config.files);
return Promise.all(
filesArray.map(file => uploadToServer(file))
);
}
// Funciona con uno o múltiples archivos
uploadFiles({ files: singleFile });
uploadFiles({ files: [file1, file2, file3] });
Con Props de React/Angular
interface ButtonProps {
className?: string | string[];
}
function Button({ className }: ButtonProps) {
const classes = toArray(className || []).join(' ');
return <button className={classes}>Click me</button>;
}
<Button className="primary" />
<Button className={['primary', 'large', 'rounded']} />
Casos de Uso Comunes
- APIs flexibles: Cuando un campo puede ser string o array
- Query parameters: URLs con parámetros únicos o múltiples
- Form inputs: Normalizar valores de inputs
- Props de componentes: Aceptar className como string o array
- Configuración: Opciones que pueden ser singulares o múltiples
- Migraciones: Compatibilidad entre versiones de API
Notas Técnicas
- Type checking: Usa
Array.isArray()nativo para verificar - Inmutabilidad: Si ya es array, retorna la misma referencia (no copia)
- Performance: O(1) - solo verifica tipo y envuelve si necesario
- Null/Undefined: No filtra valores null/undefined, los incluye en array
- Tipo de retorno: Siempre
string[]según implementación actual - Arrays vacíos:
toArray([])retorna[]
Limitaciones
Tipo de Retorno
La implementación actual siempre retorna string[]. Para otros tipos, considera usar:
function toTypedArray<T>(value: T | T[]): T[] {
return Array.isArray(value) ? value : [value];
}
Implementación
export const toArray = (value: any): string[] =>
Array.isArray(value) ? value : [value];
Ver También
- distinct - Eliminar duplicados de arrays
- arrayGroupBy - Agrupar elementos de array