[javascript] Underscore.js를 사용하여 JSON 데이터를 조작하는 방법은 어떻게 되나요?
- Underscore.js 설치하기: 먼저, 프로젝트에 Underscore.js를 설치해야 합니다. 다음 명령어를 사용하여 npm을 통해 설치할 수 있습니다.
npm install underscore
- Underscore.js 라이브러리 불러오기: JSON 데이터를 조작하기 위해 Underscore.js를 불러와야 합니다. 다음과 같이
require
메서드를 사용하여 라이브러리를 불러올 수 있습니다.
const _ = require('underscore');
- JSON 데이터 조작하기: 이제 Underscore.js를 사용하여 JSON 데이터를 조작할 수 있습니다. 다음은 몇 가지 주요 함수의 예시입니다.
_.each()
: JSON 데이터의 각 항목에 대해 작업을 반복합니다._.each(jsonData, function(item) { // 항목에 대한 작업 수행 });
_.filter()
: 조건에 맞는 항목만 필터링합니다.const filteredData = _.filter(jsonData, function(item) { return item.age > 18; });
_.map()
: 각 항목을 새로운 값으로 매핑합니다.const mappedData = _.map(jsonData, function(item) { return item.name; });
_.reduce()
: 항목을 하나의 값으로 축소합니다.const reducedData = _.reduce(jsonData, function(memo, item) { return memo + item.age; }, 0);
_.pluck()
: 특정 속성 값을 추출합니다.const pluckedData = _.pluck(jsonData, 'name');
위 예시는 일부 일반적인 방법으로 JSON 데이터를 조작하는 방법을 보여줍니다. 사례에 따라 다른 Underscore.js 함수를 적용하거나 여러 함수를 연결하여 원하는 결과를 얻을 수 있습니다.
더 자세한 사용 방법과 함수 목록은 Underscore.js 공식 문서를 참조하세요: Underscore.js 공식 문서