Tutorial Array of Objek JavaScript - Cara Membuat, Mengemas kini, dan Melingkari Objek Dengan Kaedah JS Array

Rata-rata saya bekerja dengan data JSON 18 kali seminggu. Dan saya masih perlu google untuk kaedah tertentu untuk memanipulasinya hampir setiap masa. Bagaimana jika ada panduan utama yang selalu dapat memberi anda jawapan?

Dalam artikel ini, saya akan menunjukkan kepada anda asas-asas bekerja dengan susunan objek dalam JavaScript.

Sekiranya anda pernah bekerja dengan struktur JSON, anda telah bekerja dengan objek JavaScript. Cukup harfiah. JSON bermaksud Notasi Objek JavaScript.

Membuat objek semudah ini:

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

Objek ini mewakili sebuah kereta. Terdapat banyak jenis dan warna kereta, setiap objek kemudian mewakili kereta tertentu.

Sekarang, selalunya anda mendapat data seperti ini dari perkhidmatan luaran. Tetapi kadang-kadang anda perlu membuat objek dan susunannya secara manual. Seperti yang saya lakukan semasa membuat e-kedai ini:

Memandangkan setiap item senarai kategori kelihatan seperti ini dalam HTML:

Saya tidak mahu kod ini diulang 12 kali, yang menjadikannya tidak dapat dicapai.

Membuat susunan objek

Tetapi mari kita kembali ke kereta. Mari lihat set kereta ini:

Kami dapat menggambarkannya sebagai susunan dengan cara ini:

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 }, { ... }, ... ] 

Susunan objek tidak tetap sama sepanjang masa. Kita hampir selalu perlu memanipulasi mereka. Oleh itu mari kita lihat bagaimana kita dapat menambahkan objek ke array yang sudah ada.

Tambahkan objek baru pada permulaan - Array.unshift

Untuk menambah objek pada kedudukan pertama, gunakan Array.unshift.

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

Tambahkan objek baru di hujung - Array.push

Untuk menambahkan objek pada kedudukan terakhir, gunakan Array.push.

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

Tambahkan objek baru di tengah - Array.splice

Untuk menambah objek di tengah, gunakan Array.splice. Fungsi ini sangat berguna kerana dapat juga membuang barang. Perhatikan parameternya:

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

Oleh itu, jika kita mahu menambah Volkswagen Cabrio merah di kedudukan kelima, kita akan menggunakan:

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

Mengulangi pelbagai objek

Izinkan saya mengemukakan soalan di sini: Mengapa anda mahu melengkapkan pelbagai objek? Sebab saya bertanya adalah bahawa perulangan hampir tidak pernah menjadi penyebab utama dari apa yang ingin kita capai.

JavaScript menyediakan banyak fungsi yang dapat menyelesaikan masalah anda tanpa benar-benar menerapkan logik dalam kitaran umum. Mari kita lihat.

Cari objek dalam array mengikut nilainya - Array.find

Katakan kita mahu mencari kereta yang berwarna merah. Kita boleh menggunakan fungsinya Array.find.

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

Fungsi ini mengembalikan elemen pencocokan pertama:

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

Anda juga boleh mencari pelbagai nilai:

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

Sekiranya kita mendapat kereta terakhir dalam senarai.

Dapatkan banyak item dari array yang sesuai dengan syarat - Array.filter

Yang Array.findmengembalikan hanya satu objek. Sekiranya kita mahu mendapatkan semua kereta merah, kita perlu menggunakan 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 //  } // ] 

Ubah objek larik - Array.map

Ini adalah sesuatu yang sangat kita perlukan. Ubah susunan objek menjadi susunan objek yang berbeza. Itu tugas untuk Array.map. Katakan kita mahu mengelaskan kereta kita kepada tiga kumpulan berdasarkan ukurannya.

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'] 

Kita juga boleh membuat objek baru jika kita memerlukan lebih banyak nilai:

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' }, // ... // ] 

Tambahkan properti ke setiap objek array - 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 :-)