Saltar al contenido principal

getObjectByValue / getObjIndexByValue

Paquete: @tiendana/utils

Funciones para buscar objetos en arrays por campo y valor. getObjectByValue retorna el objeto encontrado, getObjIndexByValue retorna su índice.

Características​

✅ Búsqueda por campo y valor
✅ Soporta búsqueda en propiedades anidadas
✅ Retorna primera coincidencia
✅ Performance O(n)

getObjectByValue​

Busca y retorna el primer objeto que tenga un campo con un valor específico.

Firma​

function getObjectByValue(
array: any[],
field: string | number,
value: any
): {} | undefined

Parámetros​

ParámetroTipoDescripciónRequerido
arrayany[]Array de objetos donde buscar✅
fieldstring | numberCampo por el cual buscar✅
valueanyValor a buscar en el campo✅

Retorno​

Tipo: {} | undefined

  • El primer objeto que coincida con objeto[field] === value
  • undefined si no encuentra coincidencia

Ejemplos​

Buscar Usuario por Email​

import { getObjectByValue } from '@tiendana/utils';

const users = [
{ id: 1, name: 'Ana', email: 'ana@example.com' },
{ id: 2, name: 'Juan', email: 'juan@example.com' },
{ id: 3, name: 'María', email: 'maria@example.com' }
];

const user = getObjectByValue(users, 'email', 'juan@example.com');
// { id: 2, name: 'Juan', email: 'juan@example.com' }

const notFound = getObjectByValue(users, 'email', 'no-existe@example.com');
// undefined

Buscar Producto por SKU​

const products = [
{ sku: 'PROD-001', name: 'Laptop', price: 999 },
{ sku: 'PROD-002', name: 'Mouse', price: 29 },
{ sku: 'PROD-003', name: 'Keyboard', price: 79 }
];

const product = getObjectByValue(products, 'sku', 'PROD-002');
// { sku: 'PROD-002', name: 'Mouse', price: 29 }

Buscar por ID Numérico​

const items = [
{ id: 1, title: 'Item 1' },
{ id: 2, title: 'Item 2' },
{ id: 3, title: 'Item 3' }
];

const item = getObjectByValue(items, 'id', 2);
// { id: 2, title: 'Item 2' }

Con Type Guard​

interface User {
id: number;
name: string;
email: string;
}

function findUserByEmail(users: User[], email: string): User | null {
const user = getObjectByValue(users, 'email', email);
return user ? user as User : null;
}

getObjIndexByValue​

Busca y retorna el índice del primer objeto que coincida con el campo y valor.

Firma​

function getObjIndexByValue(
array: any[],
field: string | number,
value: any
): number | undefined

Parámetros​

ParámetroTipoDescripciónRequerido
arrayany[]Array de objetos donde buscar✅
fieldstring | numberCampo por el cual buscar✅
valueanyValor a buscar en el campo✅

Retorno​

Tipo: number | undefined

  • Índice del primer objeto que coincida
  • undefined si no encuentra coincidencia

Ejemplos​

Obtener Índice para Actualizar​

import { getObjIndexByValue } from '@tiendana/utils';

const products = [
{ id: 1, name: 'Product A', stock: 10 },
{ id: 2, name: 'Product B', stock: 5 },
{ id: 3, name: 'Product C', stock: 0 }
];

const index = getObjIndexByValue(products, 'id', 2);

if (index !== undefined) {
products[index] = { ...products[index], stock: 15 };
}

Eliminar Elemento​

const users = [
{ id: 1, name: 'Ana' },
{ id: 2, name: 'Juan' },
{ id: 3, name: 'María' }
];

const indexToDelete = getObjIndexByValue(users, 'id', 2);

if (indexToDelete !== undefined) {
users.splice(indexToDelete, 1);
}
// users ahora solo tiene Ana y María

Verificar Existencia​

function userExists(users: User[], email: string): boolean {
return getObjIndexByValue(users, 'email', email) !== undefined;
}

if (userExists(users, 'ana@example.com')) {
console.log('Usuario ya existe');
}

Mover Elemento​

const tasks = [
{ id: 1, title: 'Task 1', priority: 1 },
{ id: 2, title: 'Task 2', priority: 2 },
{ id: 3, title: 'Task 3', priority: 3 }
];

function moveToTop(taskId: number) {
const index = getObjIndexByValue(tasks, 'id', taskId);

if (index !== undefined && index > 0) {
const task = tasks.splice(index, 1)[0];
tasks.unshift(task);
}
}

moveToTop(3); // Task 3 ahora es el primero

Uso Conjunto​

Buscar y Actualizar​

// Obtener objeto
const user = getObjectByValue(users, 'id', 123);

if (user) {
// Obtener índice para actualizar
const index = getObjIndexByValue(users, 'id', 123);

if (index !== undefined) {
users[index] = { ...user, lastLogin: new Date() };
}
}

Validar y Eliminar​

function deleteProduct(products: Product[], sku: string): boolean {
const product = getObjectByValue(products, 'sku', sku);

if (!product) {
console.log('Producto no encontrado');
return false;
}

const index = getObjIndexByValue(products, 'sku', sku);

if (index !== undefined) {
products.splice(index, 1);
return true;
}

return false;
}

Casos de Uso Comunes​

  • CRUD operations: Buscar para actualizar o eliminar
  • Validaciones: Verificar existencia de elementos
  • Sincronización de datos: Encontrar elementos para actualizar
  • Gestión de estado: Localizar items en arrays de estado
  • Búsquedas simples: Alternativa a .find() y .findIndex()

Notas Técnicas​

  • Performance: O(n) - recorre el array hasta encontrar coincidencia
  • Primera coincidencia: Retorna al encontrar el primer match
  • Comparación estricta: Usa === para comparar valores
  • Propiedades anidadas: Implementación incluye búsqueda en propiedades anidadas
  • hasOwnProperty: Verifica que el objeto tenga la propiedad antes de comparar
  • Inmutabilidad: No modifica el array original

Alternativas Nativas​

// Equivalente con Array.find()
const user = users.find(u => u.email === 'ana@example.com');

// Equivalente con Array.findIndex()
const index = users.findIndex(u => u.email === 'ana@example.com');
Cuándo usar cada una
  • getObjectByValue/getObjIndexByValue: Búsquedas simples por campo específico
  • Array.find()/findIndex(): Búsquedas complejas con lógica custom

Implementación​

export function getObjectByValue(
array: any[],
field: string | number,
value: any
): {} | undefined {
for (let i = 0; i < array.length; i++) {
if (array[i].hasOwnProperty(field)) {
if (array[i][field] === value) {
return array[i];
} else {
// Búsqueda en propiedades anidadas
for (const prop in array[i][field]) {
if (array[i][field][prop] === value) {
return array[i];
}
}
}
}
}
}

export function getObjIndexByValue(
array: any[],
field: string | number,
value: any
): number | undefined {
for (let i = 0; i < array.length; i++) {
if (array[i].hasOwnProperty(field)) {
if (array[i][field] === value) {
return i;
} else {
for (const prop in array[i][field]) {
if (array[i][field][prop] === value) {
return i;
}
}
}
}
}
}

Ver También​