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