2017-03-17 45 views
0

鑑於這種JSON對象(從壞的API):如何解構對象的數組?

{ 
    "Person": { 
     "UID": 78, 
     "Name": "Brampage", 
     "Surname": "Foo" 
    }, 
    "Notes": [ 
     { 
      "UID": 78, 
      "DateTime": "2017-03-15T15:43:04.4072317", 
      "Person": { 
       "Name": "Brampage", 
       "Surname": "Foo" 
      }, 
      **"Note":** { 
       "Title": "Lorem Ipsum...", 
       "Content": "Blaat blaat blaat blaat ..." 
      } 
     }, 
     { 
      "UID": 78, 
      "DateTime": "2017-03-15T15:43:04.4072317", 
      "Person": { 
       "Name": "Brampage", 
       "Surname": "Foo" 
      }, 
      "Note": { 
       "Title": "Lorem Ipsum...", 
       "Content": "Blaat blaat blaat blaat ..." 
      } 
     } 
     // etc. 
    ] 
} 

我應該如何解構此對象,我會留下來與此數據:人,Notes.Note []。

這就是我試圖實現以上,但它不工作:

this.http.get(url) 
.map(res => { 
    const jsonObject = res.json(); 

    // Destructuring 
    const { Person} = jsonObject; 
    const [{ Note }] = jsonObject.Notes; 

    return { 
     person: Person, 
     note:[ 
      Note 
     ] 
    } 
}) 
.subscribe(
    usefullInformation => { 
     console.log(usefullInformation); 
    }, 
    error => { 
    } 
); 

這是打字稿對如何解構文檔:TypeScript Destructuring Documenation

+0

不能做到這一點與解構。只需使用普通的點訪問和'map'。 – Ryan

回答

1

正如Ryan說,你需要序列化您的數據手工。因爲解構不處理條件語句。我建議你寫一個序列化函數,在數據上調用Observable.map

例如:

const data = { 
 
    "Person": { 
 
     "UID": 78, 
 
     "Name": "Brampage", 
 
     "Surname": "Foo" 
 
    }, 
 
    "Notes": [ 
 
     { 
 
      "UID": 78, 
 
      "DateTime": "2017-03-15T15:43:04.4072317", 
 
      "Person": { 
 
       "Name": "Brampage", 
 
       "Surname": "Foo" 
 
      }, 
 
      "Note": { 
 
       "Title": "Lorem Ipsum...", 
 
       "Content": "Blaat blaat blaat blaat ..." 
 
      } 
 
     }, 
 
     { 
 
      "UID": 78, 
 
      "DateTime": "2017-03-15T15:43:04.4072317", 
 
      "Person": { 
 
       "Name": "Brampage", 
 
       "Surname": "Foo" 
 
      }, 
 
      "Note": { 
 
       "Title": "Lorem Ipsum...", 
 
       "Content": "Blaat blaat blaat blaat ..." 
 
      } 
 
     } 
 
    ] 
 
} 
 

 
function getNotesFor(uid, notes) { 
 
    return notes 
 
    .filter(item => item.UID === uid) 
 
    .map(item => item.Note); 
 
} 
 

 
const { Person } = data; 
 
const Notes = getNotesFor(Person.UID, data.Notes); 
 

 
console.log(Person, Notes);

+0

既然解構不可能,我接受這個答案,謝謝你的明確解決方案,我想我可能忽略了一些東西。 – Brampage