JavaScript

[TypeScript] reduce 사용하기 (array to object)

hid1 2023. 7. 6. 22:49
// before
[
  {
    name: "A",
    age: 16
  },
  {
    name: "B",
    age: 22
  }
]


// after
{
    "A": 16
    "B": 22
}
const result = data.reduce((acc, cur) => {
  acc[cur.name] = cur.age
  return acc
}, {})

위와 같은 배열을 아래와 같이 객체로 변환하기 위해 reduce 메서드를 사용하게 되었다.

타입스크립트 쪽에서 다음과 같은 오류 메시지가 나타났다.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.

 

해당 오류 메시지는 "빈 객체에는 문자열로 인덱싱할 수 있는 인덱스 시그니처가 없으므로, 문자열로 속성을 접근하는 것은 허용되지 않는다"는 의미이다.

이를 해결하기 위해 스택오버플로우를 검색하니까  해결 방법을 금방 찾을 수 있었다.

 

TS - Reduce an array of objects to an object

I want to convert an array of objects to an object var arrays = [ {key:'k1',value:'v1'}, {key:'k2',value:'v2'}, {key:'k3',value:'v3'} ]; to {k1: "v1", k2: "v2", k3:...

stackoverflow.com

const result = data.reduce((acc, cur) => {
  acc[cur.name] = cur.age
  return acc
}, {} as Record<string, number>)

초기값에 'as' 키워드를 사용하여 타입을 명시적으로 지정해줌으로써 해결을 하였다.

 

 

 

 

반응형