Ape*_*pex 1 arrays key angular
我有一个对象数组,其格式如下:
{
"gallery": [{
"id": 606,
"status": 1,
"name": "00000000606.png",
"title": "splash.png",
"location": "",
"caption": "",
"type": "image/png",
"charset": "binary",
"tags": "",
"width": 2732,
"height": 2732,
"size": 476358,
"embed_id": null,
"user": 1,
"date_uploaded": "2019-09-26T05:22:31-04:00",
"storage_adapter": "local",
"url": "/storage/uploads/00000000606.png",
"thumbnail_url": "/storage/uploads/thumbs/606.png",
"old_thumbnail_url": "/storage/uploads/thumbs/00000000606-png-160-160-true.jpg",
"html": null
}, {
"id": 610,
"status": 1,
"name": "00000000610.png",
"title": "icon.png",
"location": "",
"caption": "",
"type": "image/png",
"charset": "binary",
"tags": "",
"width": 1024,
"height": 1024,
"size": 274477,
"embed_id": null,
"user": 1,
"date_uploaded": "2019-09-26T06:43:44-04:00",
"storage_adapter": "local",
"url": "/storage/uploads/00000000610.png",
"thumbnail_url": "/storage/uploads/thumbs/610.png",
"old_thumbnail_url": "/storage/uploads/thumbs/00000000610-png-160-160-true.jpg",
"html": null
}]
}
Run Code Online (Sandbox Code Playgroud)
我想做的是设置要发布的数据,如下所示:
{
gallery: [
{id: 606},
{id: 610}
]
}
Run Code Online (Sandbox Code Playgroud)
我试着做:
const imageId = this.selectedGallery.map(({id}) => id );
Run Code Online (Sandbox Code Playgroud)
然后像这样设置图库数组:
{
gallery: [
{id: imageId},
]
}
Run Code Online (Sandbox Code Playgroud)
这会将完整的数组发布到id:并失败。
我将如何处理?
小智 5
When you use that kind of one-liner, you have a specific syntax to follow :
.map( ( { id } ) => ( { id } ) );
_|_ _|_ _|_ _|_ _|_ _|_ _|_ _|_
1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)
1 - the operator you are going to use
2 - the parenthesis that will be used to contain your parameters declaration. You can omit it if you have a single parameter. In TS, if you type it, you're forced to put the parenthesis anyway.
3 - The deconstruction bracket. Between those brackets, you can selectively pick properties in your object. In your case, you are picking only the ID.
4 - the properties to pick (1 or more, comma separated)
5 - The fat arrow to write a one-liner
6 - The evaluating parenthesis : this one is a bit tricky, a Stack answer wouldn't even be enough to explain it. The best to understand it is to play with it. In this case, see that parenthesis as a way of returning an object : since the function body (function() {}) and object declaration (obj = {}) use the same bracketed-syntax, the parenthesis changes it to return an object instead of a function body.
7 - the bracket for the object declaration
8 - the properties to use. When writing a single property ({ id } instead of { id: id }), it simply reduces the syntax but prevents from doing changes to that variable.
The final syntax would then be
.map(({ id }) => ({ id }))
Run Code Online (Sandbox Code Playgroud)