2017-11-02 18 views
1

우리는 검색 입력으로부터 자동 제안을 가지고 있습니다. 반환되는 배열은이 모델에 해당합니다.그룹화 된 개체 (그룹화 된 결과의 하위 항목에서 다른 속성 추출하기)

AutoSuggest[] = 
[ 
    {category: "CAR", type: "COMMON", suggests: ['ford', 'jeep']}, 
    {category: "TRAVEL", type: "SHORT", suggests: ['tokyo', 'paris', 'london']}, 
    {category: "TRAVEL", type: "LONG", suggests: ['costa rica', 'greenland']}} 
] 

우리는 범주를 병합하지만 값을 유지하고 두 개의 다른 배열 항목으로 구분하여 결과를 얻고 싶습니다. 그것은 다음과 같을 것이다 :

[ 
    { 
     category: "CAR", 
     values: [ 
      { type: "COMMON", suggests: ['ford', 'jeep'] } 
     ] 
    }, 
    { 
     category: 'TRAVEL', 
     values: [ 
      { type: "SHORT", suggests: ['tokyo', 'paris', 'london'] }, 
      { TYPE: "LONG", suggests: ['costa rica', 'greenland'] } 
     ] 
    } 
] 

가 lodash groupBy과 노력, 우리는 단순히 우리의 자동차와 여행 목적에 배치 제안되었다. 그러나 우리가 원래 대상의 일부를 "추출"해야하기 때문에 우리의 요구에 맞지 않습니다.

답변

2

해시 테이블을 사용하여 동일한 범주로 그룹화 할 수 있습니다.

2

var data = [{ category: "CAR", type: "COMMON", suggests: ['ford', 'jeep'] }, { category: "TRAVEL", type: "SHORT", suggests: ['tokyo', 'paris', 'london'] }, { category: "TRAVEL", type: "LONG", suggests: ['costa rica', 'greenland'] }], 
 
    hash = Object.create(null), 
 
    grouped = []; 
 

 
data.forEach(function (o) { 
 
    if (!hash[o.category]) { 
 
     hash[o.category] = { category: o.category, values: [] }; 
 
     grouped.push(hash[o.category]); 
 
    } 
 
    hash[o.category].values.push({ type: o.type, suggests: o.suggests }); 
 
}); 
 

 
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

당신이 lodash을 사용하고 있기 때문에.
당신은 필요한 결과를 반환

const data = [ 
    {category: "CAR", type: "COMMON", suggests: ['ford', 'jeep']}, 
    {category: "TRAVEL", type: "SHORT", suggests: ['tokyo', 'paris', 'london']}, 
    {category: "TRAVEL", type: "LONG", suggests: ['costa rica', 'greenland']} 
] 
const grouped = _.chain(data).groupBy('category').map((values,category)=> ({category,values})).value() 

console.log(grouped) 

뭔가를 할 수 있습니다.

1
결과는 ES6 Array.prototype.reduce ANB AutoSuggest와 초기 데이터 배열 Array.prototype.filter 방법을 얻을 수

:

let result = AutoSuggest.reduce((acc, i) => { 
    const value = { type: i.type, suggests: i.suggests }; 
    const found = acc.find(j => j.category === i.category); 
    if(found) { 
    found.values.push(value); 
    } 
    else { 
    acc.push({ category: i.category, values: [ value ] }); 
    } 
    return acc; 
}, []);