Tutorial de matriz de objetos de JavaScript: cómo crear, actualizar y recorrer objetos mediante métodos de matriz JS

En promedio, trabajo con datos JSON 18 veces a la semana. Y todavía necesito buscar en Google formas específicas de manipularlos casi siempre. ¿Y si hubiera una guía definitiva que siempre pudiera darte la respuesta?

En este artículo, le mostraré los conceptos básicos para trabajar con matrices de objetos en JavaScript.

Si alguna vez trabajó con una estructura JSON, ha trabajado con objetos JavaScript. Bastante literal. JSON son las siglas de JavaScript Object Notation.

Crear un objeto es tan simple como esto:

{ "color": "purple", "type": "minivan", "registration": new Date('2012-02-03'), "capacity": 7 } 

Este objeto representa un automóvil. Puede haber muchos tipos y colores de automóviles, cada objeto representa un automóvil específico.

Ahora, la mayoría de las veces obtiene datos como este de un servicio externo. Pero a veces es necesario crear objetos y sus matrices manualmente. Como hice cuando estaba creando esta tienda electrónica:

Teniendo en cuenta que cada elemento de la lista de categorías se ve así en HTML:

No quería que este código se repitiera 12 veces, lo que lo haría imposible de mantener.

Creando una matriz de objetos

Pero volvamos a los coches. Echemos un vistazo a este conjunto de coches:

Podemos representarlo como una matriz de esta manera:

let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ] 

Las matrices de objetos no permanecen iguales todo el tiempo. Casi siempre necesitamos manipularlos. Entonces, echemos un vistazo a cómo podemos agregar objetos a una matriz ya existente.

Agregue un nuevo objeto al principio: Array.unshift

Para agregar un objeto en la primera posición, use Array.unshift.

let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.unshift(car); 

Agregue un nuevo objeto al final: Array.push

Para agregar un objeto en la última posición, use Array.push.

let car = {  "color": "red",  "type": "cabrio",  "registration": new Date('2016-05-02'),  "capacity": 2 } cars.push(car); 

Agregue un nuevo objeto en el medio: Array.splice

Para agregar un objeto en el medio, use Array.splice. Esta función es muy útil ya que también puede eliminar elementos. Cuidado con sus parámetros:

Array.splice( {index where to start}, {how many items to remove}, {items to add} ); 

Entonces, si queremos agregar el Volkswagen Cabrio rojo en la quinta posición, usaríamos:

let car = {  "color": "red",  "type": "cabrio",  "registration": new Date('2016-05-02'),  "capacity": 2 } cars.splice(4, 0, car); 

Recorrer una variedad de objetos

Déjame hacerte una pregunta aquí: ¿Por qué quieres recorrer una matriz de objetos? La razón por la que pregunto es que el bucle casi nunca es la causa principal de lo que queremos lograr.

JavaScript proporciona muchas funciones que pueden resolver su problema sin realmente implementar la lógica en un ciclo general. Vamos a ver.

Encuentre un objeto en una matriz por sus valores - Array.find

Digamos que queremos encontrar un coche rojo. Podemos usar la función Array.find.

let car = cars.find(car => car.color === "red"); 

Esta función devuelve el primer elemento coincidente:

console.log(car); // output: // { //   color: 'red', //   type: 'station wagon', //   registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', //   capacity: 5 // } 

También es posible buscar varios valores:

let car = cars.find(car => car.color === "red" && car.type === "cabrio");

En ese caso, obtendremos el último automóvil de la lista.

Obtenga varios elementos de una matriz que coincidan con una condición: Array.filter

La Array.findfunción devuelve solo un objeto. Si queremos conseguir todos los coches rojos, tenemos que utilizar Array.filter.

let redCars = cars.filter(car => car.color === "red"); console.log(redCars); // output: // [ // { //    color: 'red', //    type: 'station wagon', //    registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', //    capacity: 5 //  }, // { //    color: 'red', //    type: 'cabrio', //    registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)', //    capacity: 2 //  } // ] 

Transformar objetos de una matriz - Array.map

Esto es algo que necesitamos con mucha frecuencia. Transforma una matriz de objetos en una matriz de diferentes objetos. Eso es un trabajo Array.map. Digamos que queremos clasificar nuestros coches en tres grupos según su tamaño.

let sizes = cars.map(car => { if (car.capacity <= 3){ return "small"; } if (car.capacity <= 5){ return "medium"; } return "large"; }); console.log(sizes); // output: // ['large','medium','medium', ..., 'small'] 

También es posible crear un nuevo objeto si necesitamos más valores:

let carsProperties = cars.map(car => { let properties = { "capacity": car.capacity, "size": "large" };  if (car.capacity <= 5){    properties['size'] = "medium";  }  if (car.capacity <= 3){    properties['size'] = "small";  } return properties; }); console.log(carsProperties); // output: // [ //   { capacity: 7, size: 'large' }, //   { capacity: 5, size: 'medium' }, //   { capacity: 5, size: 'medium' }, //   { capacity: 2, size: 'small' }, // ... // ] 

Agregue una propiedad a cada objeto de una matriz: Array.forEach

But what if we want the car object too? In that case we can enhance the object for a new property size. This is a good use-case for the Array.forEach function.

cars.forEach(car => { car['size'] = "large";  if (car.capacity <= 5){    car['size'] = "medium";  }  if (car.capacity <= 3){    car['size'] = "small";  } }); 

Sort an array by a property - Array.sort

When we're done with transforming the objects, we usually need to sort them one way or another.

Typically, the sorting is based on a value of a property every object has. We can use the Array.sort function, but we need to provide a function that defines the sorting mechanism.

Let's say we want to sort the cars based on their capacity in descending order.

let sortedCars = cars.sort((c1, c2) => (c1.capacity  c2.capacity) ? -1 : 0); console.log(sortedCars); // output: // [ // { // color: 'purple', // type: 'minivan', // registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)', // capacity: 7 // }, // { // color: 'red', // type: 'station wagon', // registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', // capacity: 5 // }, // ... // ] 

The Array.sort compares two objects and puts the first object in the second place if the result of the sorting function is positive. So you can look at the sorting function as if it was a question: Should the first object be placed in second place?

Make sure to always add the case for zero when the compared value of both objects is the same to avoid unnecessary swaps.

Checking if objects in array fulfill a condition - Array.every, Array.includes

Array.every and Array.some come handy when we just need to check each object for a specific condition.

Do we have a red cabrio in the list of cars? Are all cars capable of transporting at least 4 people? Or more web-centric: Is there a specific product in the shopping cart?

cars.some(car => car.color === "red" && car.type === "cabrio"); // output: true cars.every(car => car.capacity >= 4); // output: false 

You may remember the function Array.includes which is similar to Array.some, but works only for primitive types.

Summary

In this article, we went through the basic functions that help you create, manipulate, transform, and loop through arrays of objects. They should cover most cases you will stumble upon.

If you have a use-case that requires more advanced functionality, take a look at this detailed guide to arrays or visit the W3 schools reference.

Or get in touch with me and I will prepare another article :-)