2017-04-11 81 views
-1

讓我從一個JSON對象開始喜歡獨特的分JSON的一個JSON的

[ 
    { 
    "id": 32837732, 
    "composer": { 
     "id": 536, 
     "name": "Francis Poulenc" 
    }, 
    "title": "Of Thee I Sing: Overture (radio version)" 
    }, 
    { 
    "id": 32837735, 
    "composer": { 
     "id": 245, 
     "name": "George Gershwin" 
    }, 
    "title": "Concerto in F : I. Allegro" 
    }, 
    { 
    "id": 32837739, 
    "composer": { 
     "id": 245, 
     "name": "George Gershwin" 
    }, 
    "title": "Concerto in F : II. Adagio" 
    } 
] 

是有可能得到,在乾淨的,聲明的方式,一個JSON像

{ 
'composer': [ 
       { 
       'id': '536', 
       'name': 'Francis Poulenc' 
       }, 
       { 
       'id': '245', 
       'name': 'George Gershwin' 
       }, 
     ] 
} 

也就是說每個作曲家(id和名字)的獨特的子值?

+0

這不可讀的,把它放在代碼格式... –

回答

0

var arr= [ 
 
    { 
 
    "id": 32837732, 
 
    "composer": { 
 
     "id": 536, 
 
     "name": "Francis Poulenc" 
 
    }, 
 
    "title": "Of Thee I Sing: Overture (radio version)" 
 
    }, 
 
    { 
 
    "id": 32837735, 
 
    "composer": { 
 
     "id": 245, 
 
     "name": "George Gershwin" 
 
    }, 
 
    "title": "Concerto in F : I. Allegro" 
 
    }, 
 
    { 
 
    "id": 32837739, 
 
    "composer": { 
 
     "id": 245, 
 
     "name": "George Gershwin" 
 
    }, 
 
    "title": "Concerto in F : II. Adagio" 
 
    } 
 
]; 
 

 
var composers=[]; 
 
arr.forEach(function(arrElem){ 
 
    if(arrElem.composer && !composers.some(function(comp) { return comp.id === arrElem.composer.id && comp.name === arrElem.composer.name })) 
 
      composers.push(arrElem.composer); 
 
}); 
 
alert(JSON.stringify(composers));

+0

謝謝,您的代碼段工程完美這裏... 可惜我忘了說,我在C#我的工作.. 。 請再次幫忙! –