2. FrontEnd/Javascript
[JS] JSON.stringify(…) 스프레드 연산자를 사용하면?
HyunJeongE
2025. 2. 27. 15:43
728x90
[문제]
프로젝트를 하면서, 배열을 stringify를 하면 마지막값만 저장되는 현상이 있음
localStorage.setItem(‘history’, JSON.stringify(…curHistory))
return […curHistory]
[원인]
스프레드 연산지 오용 사용
- JSON.stringify(…curHistory) = 잘못된 문법
- …curHistory는 배열을 해체하는 문법인데, JSON.stringify는 하나의 값만 받을 수 있음
- 스프레드 연산자는 배열을 개별요소로 해체하기에 올바른 형태가 아님
2. 마지막 값만 저장되는 이유
- 잘못된 스프레드 사용으로 직렬화가 실패하거나, localStorage.setItem이 유효한 데이터를 받지 못해 덮어쓰기가 발생한 것
[해결]
배열 자체를 JSON.stringify에 전달하려면 스프레드 연산자를 사용할 필요가 없음
// 올바른 코드
localStorage.setItem('history', JSON.stringify(curHistory));
return [...curHistory];
- JSON.stringify(curHistory) : 배열을 직렬화하여 문자열로 변환
- return […curHistory] : 배열을 복사하여 새로운 배열 반환
이렇게 하면 기존 배열을 유지하면서 새로운 데이터가 누적됨
예를들어, 데이터 추가시 올바른 방식은
새로운 데이터를 히스토리에 추가 저장하는 상황이라면 아래처럼 써야한다
const curHistory = JSON.parse(localStorage.getItem('history')) || [];
function addHistory(newItem) {
const updatedHistory = [...curHistory, newItem]; // 새 항목 추가
localStorage.setItem('history', JSON.stringify(updatedHistory)); // 로컬스토리지에 저장
return updatedHistory;
}
console.log(addHistory({ url: 'qqq.qqqq' }));