본문 바로가기
it/web_dev

javascript의 배열을 객체로 변경하기

by holims 2023. 6. 26.

목차

    반응형

    배열객체형태의 데이터에서 프로퍼티의 값을 새로 객체 형식으로 변한하는 방법이 무엇인지 알아보겠습니다.

     

    문제 코드

    const arr = [
      { category: "LGT", fcstValue: "0" },
      { category: "PTY", fcstValue: "0" },
      { category: "SKY", fcstValue: "1" },
    ];
    const types = { LGT: 0, PTY: 0, SKY: 1 };

     

    arr라는 배열 객체 코드에서 category의 값을 새로 생성할 객체의 propery로, fcstValue의 값을 새로 생성할 객체의 value로 선언하여 types라는 새로운 객체로 만들어 보겠습니다.

     

    변경하기

    let types = {};
    
    arr.forEach((element) => {
      types[element.category] = element.fcstValue;
    });

    types라는 빈 객체를 생성하고, arr을 forEach로 순회하면서 types의 property에 category값을, value에 fcstValue을 넣었습니다.

     

    다른 풀이 1

    const types = arr.reduce((acc, cur) => {
        acc[cur.category] = parseInt(cur.fcstValue);
        return acc;
    }, {});
    • reduce 초기화로 객체를 선언하고, 초기화된 객체에 키와 값의 형태로 객체에 삽입합니다.
    • 여기서 acc값이 초기화된 객체이고, cur은 현재의 배열의 요소값입니다.

     

    다른 풀이 2

    const types =  Object.fromEntries(
    	arr.map(({category, fcstValue})=>[category,fcstValue])
    )
    
    arr.map((value) => [value.category, value.fcstValue])
    -> 구조분해 할당 : arr.map(({ category, fcstValue }) => [category, fcstValue])
    // [ [ 'LGT', '0' ], [ 'PTY', '0' ], [ 'SKY', '1' ] ]
    
    배열에서 fromEntries을 선언하면 이중 배열에서 요소가 객체의 키와 value로 변환된다.
    // [ [ 'LGT', '0' ], [ 'PTY', '0' ], [ 'SKY', '1' ] ]
    -> // { LGT: '0', PTY: '0', SKY: '1' }