2014-12-24 2 views
0

데이터베이스의 데이터로 작업 할 때 우리는 종종 데이터베이스 제약으로 인해 복합 색인에 의해 (고유하게) 색인 될 수있는 자료 배열을 얻습니다. 그러나 indexBy은 복합 색인에 대해 작동하지 않는 것으로 보이거나 그렇지 않습니까? 로다시/밑줄이있는 복합 색인

내가 각각 ab, 색인 x의 모든 객체를 포함하는 사전의 사전을 갖고 싶어, 속성 ab이 객체와 배열 x을 감안할 때. 예 :

Fiddle here.

var x = [ 
    { 
     a: 1, 
     b: 11, 
     c: 101 
    }, 
    { 
     a: 2, 
     b: 11, 
     c: 101 
    }, 
    { 
     a: 1, 
     b: 11, 
     c: 102 
    }, 
    { 
     a: 1, 
     b: 14, 
     c: 102 
    }, 
]; 

// index x by a, then by b, then by c  
var byABC = _.compoundIndexBy(x, ['a', 'b', 'c']); 

// there are two items in `x` with a = 1 and b = 11 
console.assert(_.size(byABC[1][11]) == 2, 'Something went wrong...'); 

// display result 
console.log(byABC); 

byABC 이제 다음과 같습니다

{ 
    1: { 
     11: { 
      101: { 
       a: 1, 
       b: 11, 
       c: 101 
      }, 
      102: { 
       a: 1, 
       b: 11, 
       c: 102 
      } 
     }, 
     14: { 
      102: { 
       a: 1, 
       b: 14, 
       c: 102 
      } 
     }, 
    } 
    2: { 
     11:{ 
      101: { 
       a: 2, 
       b: 11, 
       c: 101 
      } 
     } 
    } 
} 

This FiddlecompoundexIndexBy 기능을 보여줍니다. 내 작품은 헛되다. (Lo-Dash가 복합 색인을 실제로 지원하기 때문이다.) 아니면 적어도 개선 할 수 있을까? 당신은 믹스 인을 만들 수 있습니다

+0

원하는 결과 개체 ('byABC')를 "인쇄"하여 명확하게 할 수 있습니까? – firstdoit

+0

@ gadr90 완료. 실제로 클라이언트 측 캐시 데이터에서 데이터베이스 합성 인덱스를 시뮬레이트하기 위해 더 많은 코드를 작성했습니다. 이는 실제로 유용하고 관리하기에 필요합니다. 나는. 또한이 "인덱스 데이터 구조"에서 데이터를 추가하고 제거하는 메소드를 추가했습니다. – Domi

답변

1

이 반복적으로 그룹/색인을 객체 :

_.mixin({ 
    compoundIndexBy: function(lst, iteratees, context) { 
     if (iteratees.length === 1) 
      return _.indexBy(lst, iteratees[0], context); 

     var grouped = _.groupBy(lst, iteratees[0], context); 

     _.each(grouped, function(sublst, k) { 
      grouped[k] = _.compoundIndexBy(sublst, _.rest(iteratees), context); 
     }); 

     return grouped; 
    } 
}); 

console.dir(_.compoundIndexBy(x, ['a', 'b', 'c'])); 

당신이 주어진 인덱스와 일치하는 개체의 목록을 선호하는 경우 (비 독특한 경로의 경우, 예를 들어) :

_.mixin({ 
    compoundGroupBy: function(lst, iteratees, context) { 
     var grouped = _.groupBy(lst, iteratees[0], context); 

     if (iteratees.length === 1) 
      return grouped; 

     _.each(grouped, function(sublst, k) { 
      grouped[k] = _.compoundGroupBy(sublst, _.rest(iteratees), context); 
     }); 

     return grouped; 
    } 
}); 
console.dir(_.compoundGroupBy(x, ['a', 'b', 'c'])); 

데모 http://jsfiddle.net/nikoshr/8w4n31vb/

+0

재귀가 가장 좋은 옵션 인 것 같습니다. 당신이 나를 때려 :) – firstdoit