[Spread Operator] 배열에 특정한 인덱스의 아이템 교체

Jinseok Lee·2018년 11월 7일
1
post-thumbnail

사연

React로 서비스를 개발 하는 도중 state의 배열 값의 특정한 인덱스의 값을 변경해야 할 일이 생겼다. 막상 맞딱뜨리니까 뭔가 쉽지 않았다. Velopert님 React강의를 듣던 와중에 뭔가 배운거 같기는 한데 ㅎㅎ 머리를 쥐어짜다가 어느정도 감이 와서 해결하게 되었다. 전개연산자(Spread Operator)를 활용하였다.

간단한 예제

let arr = [1,2,3,4,5];

이 배열의 2번째 인덱스를 10으로 교환해보자.
결과 값은

[1,2,10,4,5];

가 나오도록!!

해결

const index = 2;
const newVal = 10;
arr = [
	...arr.slice(0, index),
    newVal,
    ...arr.slice(index + 1)
]

리액트 setState에서의 사용예시

const newfile = {
	s3KeyThumbnail: 'blahblah.jpg';
    size: 1024,
    ext: 'jpg'
}
this.setState(state => ({
	...state,
    files: [
    	...state.files.slice(0, index),
        newFile,
        ...state.files.slice(index + 1)
    ]
}));
profile
전 위메프, 이직준비중

4개의 댓글

comment-user-thumbnail
2018년 11월 7일

setState 구문을 imperative 스타일로 하게 해주는 immer라는 라이브러리도 있습니다.
벨로퍼트님이 소개하신 것 같은데 한 번 둘러보세요. 저한테는 spread syntax보다 편하더라구요.

1개의 답글
comment-user-thumbnail
2018년 11월 7일

전 잘 안쓰긴 하는데, 이렇게도 하더라구요

const array = [1,2,3,4,5];
const copied = array.slice();
copied[2] = 10;
const newFile =  { };
this.setState(state => {
  const updated = state.files.slice();
  updated[index] = newFile;
  return { files: updated };
});
1개의 답글