给定这个JSON对象:
{
"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.
]
}
我应该如何解构这个对象,以便我将这个数据遗留下来:Person,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关于如何构建的文档:TypeScript Destructuring Documenation
答案 0 :(得分: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);