평균적으로 일주일에 18 번 JSON 데이터로 작업합니다. 그리고 거의 매번 그들을 조작하는 구체적인 방법을 찾기 위해 구글을 검색해야합니다. 항상 답을 줄 수있는 최고의 가이드가 있다면 어떨까요?
이 기사에서는 JavaScript에서 객체 배열 작업의 기본 사항을 보여줄 것입니다.
JSON 구조로 작업 한 적이 있다면 JavaScript 객체로 작업 한 것입니다. 말 그대로. JSON은 JavaScript Object Notation을 나타냅니다.
객체 생성은 다음과 같이 간단합니다.
{ "color": "purple", "type": "minivan", "registration": new Date('2012-02-03'), "capacity": 7 }
이 개체는 자동차를 나타냅니다. 자동차에는 여러 유형과 색상이있을 수 있으며 각 개체는 특정 자동차를 나타냅니다.

이제 대부분의 경우 외부 서비스에서 이와 같은 데이터를 가져옵니다. 그러나 때로는 개체와 해당 배열을 수동으로 만들어야합니다. 이 e-shop을 만들 때했던 것처럼 :

각 카테고리 목록 항목은 HTML에서 다음과 같이 보입니다.

이 코드를 12 번 반복하여 유지 관리 할 수 없게 만들고 싶지 않았습니다.
개체 배열 만들기
하지만 다시 자동차로 돌아 갑시다. 이 자동차 세트를 살펴 보겠습니다.

다음과 같이 배열로 나타낼 수 있습니다.
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 }, { ... }, ... ]
객체 배열은 항상 동일하게 유지되지 않습니다. 우리는 거의 항상 그것들을 조작해야합니다. 따라서 이미 존재하는 배열에 객체를 추가하는 방법을 살펴 보겠습니다.
시작 부분에 새 개체 추가-Array.unshift

첫 번째 위치에 개체를 추가하려면을 사용하십시오 Array.unshift
.
let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.unshift(car);
끝에 새 개체 추가-Array.push

마지막 위치에 개체를 추가하려면을 사용하십시오 Array.push
.
let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.push(car);
중간에 새 개체 추가-Array.splice

중간에 개체를 추가하려면 Array.splice
. 이 기능은 항목을 제거 할 수도 있으므로 매우 편리합니다. 매개 변수에주의하십시오.
Array.splice( {index where to start}, {how many items to remove}, {items to add} );
따라서 5 번째 위치에 빨간색 Volkswagen Cabrio를 추가하려면 다음을 사용합니다.
let car = { "color": "red", "type": "cabrio", "registration": new Date('2016-05-02'), "capacity": 2 } cars.splice(4, 0, car);
개체 배열을 통해 반복
여기서 질문을하겠습니다. 왜 객체 배열을 반복하고 싶습니까? 내가 묻는 이유는 루핑이 우리가 달성하고자하는 일의 주된 원인이 거의 아니기 때문입니다.
JavaScript는 일반적인주기에서 실제로 논리를 구현하지 않고도 문제를 해결할 수있는 많은 기능을 제공합니다. 한 번 보자.
값으로 배열에서 객체 찾기-Array.find
빨간색 자동차를 찾고 싶다고 가정 해 보겠습니다. 함수를 사용할 수 있습니다 Array.find
.

let car = cars.find(car => car.color === "red");
이 함수는 첫 번째 일치 요소를 반환합니다.
console.log(car); // output: // { // color: 'red', // type: 'station wagon', // registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)', // capacity: 5 // }
여러 값을 검색 할 수도 있습니다.
let car = cars.find(car => car.color === "red" && car.type === "cabrio");
이 경우 목록의 마지막 차를 얻을 수 있습니다.
조건과 일치하는 배열에서 여러 항목 가져 오기-Array.filter
이 Array.find
함수는 하나의 개체 만 반환합니다. 모든 빨간 자동차를 얻으려면 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 // } // ]
배열의 객체 변형-Array.map
이것은 우리가 자주 필요로하는 것입니다. 개체 배열을 다른 개체 배열로 변환합니다. 그것은 Array.map
. 자동차를 크기에 따라 세 그룹으로 분류하려고한다고 가정 해 보겠습니다.

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']
더 많은 값이 필요한 경우 새 개체를 만들 수도 있습니다.
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' }, // ... // ]
배열의 모든 객체에 속성 추가-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 :-)