Átlagosan heti 18 alkalommal dolgozom JSON-adatokkal. És még mindig gugliznom kell azokat a konkrét módszereket, amelyekkel szinte minden alkalommal manipulálhatom őket. Mi lenne, ha lenne egy végső útmutató, amely mindig megadhatja a választ?
Ebben a cikkben bemutatom az objektum tömbök használatának alapjait a JavaScript-ben.
Ha valaha JSON struktúrával dolgozott, akkor JavaScript objektumokkal dolgozott. A szó szoros értelmében. A JSON a JavaScript Object Notation rövidítést jelenti.
Az objektum létrehozása ilyen egyszerű:
{ "color": "purple", "type": "minivan", "registration": new Date('2012-02-03'), "capacity": 7 }
Ez az objektum egy autót képvisel. Az autóknak sokféle típusa és színe lehet, minden tárgy ekkor egy adott autót képvisel.

Most legtöbbször ilyen adatokat kap egy külső szolgáltatás. De néha manuálisan kell létrehoznia az objektumokat és azok tömbjeit. Ahogy ezt az e-boltot is létrehoztam:

Figyelembe véve az egyes kategórialista elemeket, így néz ki a HTML:

Nem akartam, hogy ezt a kódot 12-szer megismételjék, ami fenntarthatatlanná tenné.
Tárgytömb létrehozása
De térjünk vissza az autókra. Vessünk egy pillantást erre az autóra:

Tömbként képviselhetjük így:
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 }, { ... }, ... ]
A tárgyak tömbje nem marad állandóan ugyanaz. Szinte mindig manipulálnunk kell őket. Vessünk egy pillantást arra, hogyan adhatunk objektumokat egy már létező tömbhöz.
Új objektum hozzáadása az elején - Array.unshift

Az első pozícióba objektum hozzáadásához használja a Array.unshift
.
let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.unshift(car);
Vegyen fel egy új objektumot a végén - Array.push

Objektum hozzáadásához az utolsó helyre használja a Array.push
.
let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.push(car);
Adjon hozzá egy új objektumot a közepére - Array.splice

A középen lévő objektum hozzáadásához használja a Array.splice
. Ez a funkció nagyon hasznos, mivel elemeket is eltávolíthat. Vigyázzon a paramétereire:
Array.splice( {index where to start}, {how many items to remove}, {items to add} );
Tehát, ha az ötödik helyre szeretnénk felvenni a piros Volkswagen Cabriót, akkor a következőket használnánk:
let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.splice(4, 0, car);
Hurok egy sor objektumon
Hadd tegyek fel itt egy kérdést: Miért akar végiglapozni egy sor objektumot? Azért kérdezem, hogy a hurkolás szinte soha nem az elsődleges oka annak, amit el akarunk érni.
A JavaScript számos olyan funkcióval rendelkezik, amelyek megoldhatják a problémát anélkül, hogy a logikát ténylegesen megvalósítanák egy általános ciklusban. Lássuk.
Találjon meg egy objektumot egy tömbben az értékei alapján - Array.find
Tegyük fel, hogy piros autót akarunk találni. Használhatjuk a függvényt Array.find
.

let car = cars.find(car => car.color === "red");
Ez a függvény adja vissza az első megfelelő elemet:
console.log(car); // output: // { // color: 'red', // type: 'station wagon', // registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', // capacity: 5 // }
Több értékre is lehet keresni:
let car = cars.find(car => car.color === "red" && car.type === "cabrio");
Ebben az esetben megkapjuk a lista utolsó autóját.
Több elemet kaphat egy tömbből, amely megfelel egy feltételnek - Array.filter
A Array.find
függvény csak egy objektumot ad vissza. Ha minden piros autót meg akarunk szerezni, akkor használnunk kell 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 // } // ]
Tömb objektumainak átalakítása - Array.map
Erre gyakran szükségünk van. Alakítsa át az objektumok tömbjét különböző objektumok tömbjévé. Ez egy munka Array.map
. Tegyük fel, hogy autóinkat méretük alapján három csoportba szeretnénk sorolni.

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']
Új objektum létrehozása akkor is lehetséges, ha több értékre van szükségünk:
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' }, // ... // ]
Tulajdonság hozzáadása egy tömb minden objektumához - 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 :-)