2017-11-02 12 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']}} 
] 

カテゴリをマージして値を保持し、2つの異なる配列エントリとして別々に入力する結果を得たいと考えています。それは次のようになります。lodash groupByにしようと

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

、我々は単に私たちはCARとTRAVELオブジェクトに配置示唆してました。しかし、元のオブジェクトの一部を "抽出"する必要があるので、私たちのニーズに合っていません。

答えて

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; }

2

あなたは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 Array.prototype.filter方法でAutoSuggest初期データ配列から得ることができる:

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; 
}, []); 
関連する問題