2017-02-28 5 views
1

以下のjsonレスポンスを配列に基づいてソートしたい。カスタムソート順配列に基づいてJSONをソートする

{ 
    "expanded": { 
     "developer": { 
      "numFound": 1, 
      "start": 0, 
      "maxScore": 0.13050619, 
      "docs": [ 
       { 
        "title": "developer" 
       } 
      ] 
     }, 
     "shop": { 
      "numFound": 1, 
      "start": 0, 
      "maxScore": 1.1272022, 
      "docs": [ 
       { 
        "title": "shop" 
       } 
      ] 
     }, 
     "support": { 
      "numFound": 84, 
      "start": 0, 
      "maxScore": 1.3669837, 
      "docs": [ 
       { 
        "title": "support" 
       } 
      ] 
     } 
    } 
} 

私は、以下のソート配列(以下同じ)でソートしたいと考えています。

[ 'shop', 'support', 'developer'] 

カスタム値に基づいてこのjsonをソートする方法はありますか?

+0

それらを配列にフィルタリングし、ソートしますか? –

答えて

3

あなたはJSONを並べ替えることはできませんが、オブジェクトの配列を作成し、並べ替えることができる。

let foo = {"expanded": {"developer": {"numFound": 1,"start": 0,"maxScore": 0.13050619,"docs": [{"title": "developer"}]},"shop": {"numFound": 1,"start": 0,"maxScore": 1.1272022,"docs": [{"title": "shop"}]},"support": {"numFound": 84,"start": 0,"maxScore": 1.3669837,"docs": [{"title": "support"}]}}}; 
 

 
let orderArr = ['shop', 'support', 'developer']; 
 

 
let res = Object.keys(foo.expanded) 
 
    .map(a => ({[a] : foo.expanded[a]})) 
 
    .sort((a,b) => (orderArr.indexOf(Object.keys(a)[0]) + 1) - (orderArr.indexOf(Object.keys(b)[0]) + 1)); 
 

 
console.log(res);

1

の注文以来、ソートする必要がないようですプロパティは明示的に定義されます。代わりに、配列に必要なオブジェクトを配置してください:

let ordered = ['shop', 'support', 'developer'].map(property => { 
    return {[property]: foo.expanded[property]}; 
}); 
関連する問題