ETC -

JavaScript - 배열의 하위 배열 까지 합치는 방법 flatMap()

  • -

JavaScript - 배열의 하위 배열 까지 합치는 방법 flatMap()

flatMap는 배열 내부의 하위 배열을 쉽게 합칠 수 있는 유용한 메서드입니다. 
이것은 API연결시 데이터가 2중배열, 3중배열으로 값들이 들어올때 유용하게 가공할수 있는 메소드 입니다.

👉🏻예시1)

const alphabets = ['a', 'b', 'c'];
const fruits = ['apple', 'banana', 'cherry'];

const flatMappedWord = alphabets.flatMap((alphabet, index) => [alphabet, fruits[index]]);
console.log(flatMappedWord)
// [ 'a', 'apple', 'b', 'banana', 'c', 'cherry' ]
// map 과의 차이점은 map 에서 한개의 깊이를  평평하게 만들어 주는 것이다.

const flatMappedWordTwo = alphabets.flatMap((alphabet, index) => [[alphabet, fruits[index]]]);
console.log(flatMappedWordTwo)
// [ [ 'a', 'apple' ], [ 'b', 'banana' ], [ 'c', 'cherry' ] ]
// 즉 return 값을 2차원 배열로 전달 받게 되면 1차원 배열로 변경하는 것이다.
  • flatMap은 map의 역활 + flat의 역활까지 해준다.
  • 즉 reutrn 받는 각각의 요소들의 깊이를 -1씩 하여 보다 평평하게하고 새로운 배열을 생성한다.

👉🏻예시2)

const exampleArray = ["a", ["b", ["c"]]];
const e = exampleArray.flatMap(x => x);
console.log(e);
// ['a', 'b', Array(1)]

const q = e.flatMap(y => y);
console.log(q)
// ['a', 'b', 'c']

👉🏻예시3)

다음 예시는 실무에서 사용하는 데이터중에서 다음과 같이 3차배열까지 계층으로 되어 있는 데이터들이 있다고 해봅시다.
여기서 내가 원하는 것은 accounts안에 있는 값들중 원하는 값들만 뽑아서 새로운 배열로 넣어 리턴받는것이다.

const data = [
  {
    "bannerSectionNo": 1,
    "label": "배너 라벨명",
    "code": "001",
    "platformDisplayPcYn": "N",
    "platformDisplayMobileYn": "N",
    "platformDisplayMobileWebYn": "N",
    "memberGradeDisplayInfo": null,
    "memberGroupDisplayInfo": null,
    "accounts": [
      {
        "accountNo": 1,
        "accountName": "구좌명",
        "displayType": "SEQUENTIAL",
        "height": 300,
        "width": 200,
        "platformDisplayPcYn": "N",
        "platformDisplayMobileYn": "N",
        "platformDisplayMobileWebYn": "N",
        "memberGradeDisplayInfo": null,
        "memberGroupDisplayInfo": null,
        "banners": [
          {
            "bannerNo": 4123,
            "name": "배너 이미지",
            "nameColor": "#000000",
            "description": "배너 이미지 설명",
            "descriptionColor": "#000000",
            "imageUrl": "http://image.toast.com/abcd/image.png",
            "landingUrlType": "IMAGE_MAP",
            "landingUrl": "http://newsection.com",
            "leftSpaceColor": "#FFFFFF",
            "rightSpaceColor": "#FFFFFF",
            "browerTargetType": "CURRENT",
            "mouseOverImageUrl": "http://image.toast.com/abcd/mouse_over.png",
            "displayPeriodType": "REGULAR",
            "displayStartYmdt": "2023-03-15T18:00:45.303831122",
            "displayEndYmdt": "2023-03-22T18:00:45.303851714",
            "displayOrder": 3,
            "videoUrl": "http://ncp-video-url.com"
          }
        ]
      }
    ]
  }
]

다음과 같이 할 수 있습니다.

const testee = (x) => {
  return x.accounts.flatMap((item, idx) => {
    return { //여기서 원하는 데이터 가공!
      bannerSectionNo: x.bannerSectionNo,
      label: x.label,
      accountNo: item.accountNo,
      accountName: item.accountName,
      bannerNo: item.banners[idx].bannerNo,
      nameColor: item.banners[idx].nameColor
    } //여기서 원하는 데이터 가공!
  });
};
const exampleArray = data.flatMap(group => testee(group));
console.log(exampleArray)

결과)👇🏻

[
  {
	accountName: "구좌명",
	accountNo: 1,
	bannerNo: 4123,
	bannerSectionNo: 1,
	label: "배너 라벨명",
	nameColor: "#000000"
  }
]
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.