2017-02-28 81 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]}; 
});