2014-04-19 6 views
1

처음으로 밑줄을 사용하면 멈추었으므로 예제를 찾을 수 없습니다.밑줄을 2 차원 배열로 뽑습니다

내 데이터는 : 내가 (여기에서 일부 도움으로) 관리가 난 건물 오전 HTML 문에 배치 다음 체인으로 연결된 명령으로 별개의 store_name을 끌어하고

[{ 
     "store_name": "Store 1", 
     "franchisee_id": "id01", 
     "dish_menu": "Breakfast", 
     "dish_count": "17" 
    }, { 
     "store_name": "Store 1", 
     "franchisee_id": "id01", 
     "dish_menu": "Light Meals", 
     "dish_count": "7" 
    }, { 
     "store_name": "Store 1", 
     "franchisee_id": "id01", 
     "dish_menu": "Sandwiches", 
     "dish_count": "12" 
    }, { 
     "store_name": "Store 2", 
     "franchisee_id": "id02", 
     "dish_menu": "Breakfast", 
     "dish_count": "7" 
    }, 
     ............ 
] 

:

:

그러나

var stores = _.chain(json).pluck("store_name").sort().uniq(true).value(); 
var tempHTML = ""; 

stores.forEach(function (entry) { 
    tempHTML = tempHTML + '<option value="' + entry + '">' + entry + '</option>'; 
}); 
나는 별개의 store_namefranchisee_id 일치 기본적으로 아래처럼 내 HTML 구축을 위해 노력하고있다

_.pluck에는 store_name 값을 사용하는 franchisee_id 값이 있습니까? 이 두 필드 사이에는 1 : 1 관계가 있으므로 "처음 발견 된"franchisee_id를 얻는 것이 좋습니다. 감사!

답변

3

당신이 원하는 순서대로 아이디/이름 쌍을 얻기 위해 이런 일을 할 수있는 :

에게
var map_id_to_name = function(m, o) { 
    m[o.franchisee_id] = o.store_name; 
    return m; 
}; 
var arrayify = function(name, id) { 
    return [ name, id ]; 
}; 
var stores = _(data).chain() 
        .reduce(map_id_to_name, { }) 
        .map(arrayify) 
        .sortBy(_.first) 
        .value(); 

데모 : stores 당신에게 배열의 배열을 줄 것이다

http://jsfiddle.net/ambiguous/9xxS6/ 당신이 회전 수 을 통해 귀하의 <option>을 구축하십시오. stores는 다음과 같을 것이다 :

[ 
    [ "Store 1", "id01" ], 
    [ "Store 2", "id02" ], 
    ... 
] 

상점 이름 번째의 내부 배열의 첫 번째 입력과 프랜차이즈 ID에있을 것이다. 모든 것이 상점 이름별로 정렬됩니다. 대소 문자를 구분하지 않으려면 대신 .sortBy(function(a) { return a[0].toLowerCase() })을 사용할 수 있습니다.

reduce(map_id_to_name, { })은 개체를 사용하여 고유 ID/이름 쌍을 수집하여 고유성을 자동으로 적용합니다 (개체의 키는 고유합니다). 그런 다음 map(arrayify)은 객체를 배열 배열로 변환하므로 객체를 정렬 할 수 있습니다. 대신 객체 배열을 사용할 수 있습니다. 이는 mapsortBy 호출에 대한 작은 변경 일뿐입니다.

1

다른 접근 방법, 결과 배열을 필터링 한 후 객체에서 원하는 정보를 추출하는 고유의 오브젝트를 얻을 수 있습니다 :

var stores = _(data).chain() 

// convert each object to {store_name: ..., franchisee_id: ...} 
.map(function(m) { 
    return _.pick(m, "store_name", "franchisee_id"); 
}) 

//keep one of each 
//can be shortened to .uniq(_.property('franchisee_id')) 
.uniq(function(m) { 
    return m.franchisee_id; 
}) 

//sort by name 
.sortBy("store_name") 

//and get the array 
.value(); 

귀하의 최종 배열이

[ 
    {store_name: "Store 1", franchisee_id: "id01"}, 
    {store_name: "Store 2", franchisee_id: "id02"} 
] 

그리고 데모에 같을 것이다 http://jsfiddle.net/mr82s/


조명으로 _.mixin 마법을 TLE, 당신은 더

_.mixin({ 
    properties: function() { 
     var args = _.toArray(arguments); 
     return function(obj) { 
      return _.pick(obj, args); 
     }; 
    } 
}); 

var stores = _(data).chain() 
.map(_.properties("store_name", "franchisee_id")) 
.uniq(_.property('franchisee_id')) 
.sortBy("store_name") 
.value() 
그것을하고보다 더 가능성이 명확하게`이중 의무를 수행 reduce` 깔끔한 방법입니다

http://jsfiddle.net/nikoshr/mr82s/1/

+0

에 응축 할 수있다. –