기본 콘텐츠로 건너뛰기

라벨이 json인 게시물 표시

오늘의 코드 - Excel 에서 Collection 까지 (feat. dot2obj)

Meteor.startup ->   if Tours.find().count() is 0     addDefault = (v)->       v.createdAt = Date.now()       v     dot2obj = (obj)->       for k,v of obj         idxes = k.split '.'         if idxes.length>0           delete obj[k]           idxes.reduce (a,b,ci,ar)->             a[b] = ar.length-1 is ci and v or a[b] or {}           , obj       obj     excel = new Excel 'xlsx'     workbook = excel.read new Buffer Assets.getBinary "fixtures.xlsx"     fixtures = excel.utils.sheet_to_json workbook.Sheets['Sheet1']     Tours.insert addDefault dot2obj obj for obj in fixtures     console.log "Tours collection initiated." 이런 코드를 만들었다. Tours 라는 collection이 비어있으면 excel 파일을 읽어서 (...

IE 10에서 JSON object 사용 시 주의점

js에서 JSON에 ,를 잘못 쓰면 IE 10에서 오류 나는 경우 발견. var obj = {   a:1,   b:1 }; 이 맞지만 var obj = {   a:1,   b:1 ,  }; 복사하기 귀찮아서 이렇게 쓰는 라이브러리들이 간혹 있음. 문제는 ,를 쓴 곳에서 오류가 발생하는 것이 아니라 그 이후 라인에서 잘못한 것처럼 보여서 잡아내기 쉽지 않다. webstorm 같은 구문검사 기능이 있는 에디터를 꼭 쓰자. 아니면 coffeescript를 쓰던가 ;p

Coffeescript 에서 Array와 Object를 다루는 방법

자바스크립트를 하다보면 JSON Object와 Array를 처리할 일이 참 많다. http://spectrumdig.blogspot.com/2012/01/array-method-iteration.html Array 의 경우 위의 글을 참조. 그런데 Object는 Array처럼 다양하고 Chaining 이 가능한 방법이 없다. 기껏해야 for (var obj in jsonObject) 정도. 게다가 속도문제도 있어서 ( http://jsperf.com/for-vs-foreach/9  참조) 가독성과 코드 단순화도 좋지만 요즘같이 Rich Web Application + Mobile Web 시대에 쓰기엔 효율이 나쁜 방법이긴 하다. coffeescript 의 경우 object 와 array 에 대해 어느정도 비슷한 처리방식을 제안한다. array : <statement> for <variable> in <array> object : <statement> for <variable>,{<variable>} in <object> 와 같은 형식이다. object 의 경우 variable 로 key, value 형식을 쓸 수 있는데 value 를 생략할 수 있다. 예를 들면 아래와 같다. console.log arr for arr in [1,2,3,4,5] console.log k,v for k,v of a:1, b:2, c:3 물론 당연히 두개를 혼합해서 쓸 수도 있다. console.log k,v for k,v of obj for obj in [ {a:1, b:2}, {a:3, b:4 }, {a:1, c:4} ] 결과는 아래와 같다. a 1 b 2 a 3 b 4 a 1 c 4 재미있는 점은 둘 다 공히 when 이라는 조건절을 넣어서 filter 를 할 수 있다. console.log k,v for k,v of a:1,...