arrays - 如何从对象数组中提取键值
问题描述
我有一个对象数组,其格式如下:
{
"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
}]
}
我想做的是将发布的数据设置如下:
{
gallery: [
{id: 606},
{id: 610}
]
}
我试图这样做:
const imageId = this.selectedGallery.map(({id}) => id );
然后像这样设置画廊数组:
{
gallery: [
{id: imageId},
]
}
这会将整个数组发布到 id: 并失败。
我将如何处理这个?
解决方案
当您使用这种单线时,您需要遵循特定的语法:
.map( ( { id } ) => ( { id } ) );
_|_ _|_ _|_ _|_ _|_ _|_ _|_ _|_
1 2 3 4 5 6 7 8
1 - 您要使用的运算符
2 - 用于包含参数声明的括号。如果你有一个参数,你可以省略它。在 TS 中,如果你键入它,无论如何你都必须加上括号。
3 - 解构支架。在这些括号之间,您可以有选择地选择对象中的属性。在您的情况下,您只选择 ID。
4 - 要选择的属性(1 个或多个,逗号分隔)
5 - 写单行字的粗箭头
6 - 评估括号:这个有点棘手,堆栈答案甚至不足以解释它。最好的理解是玩它。在这种情况下,将括号视为返回对象的一种方式:由于函数体 ( function() {}
) 和对象声明 ( obj = {}
) 使用相同的括号语法,因此括号将其更改为返回对象而不是函数体。
7 - 对象声明的括号
8 - 要使用的属性。在编写单个属性({ id }
而不是{ id: id }
)时,它只是简化了语法,但阻止了对该变量进行更改。
最终的语法将是
.map(({ id }) => ({ id }))
推荐阅读
- android - 了解 Android 上的“后退按钮”行为
- python - 在 python 中创建带有列表的数据框
- java - 带有 java11 的 Openliberty 有警告
- sql - 如何使用 dbeaver 连接到 Oracle ADW 实例
- wpf - 如何将按钮创建代码移动到样式中
- python-3.x - 如何在云函数中读取 csv 文件的创建和更新元数据并将其作为列添加到 csv
- java - 我想在登录时记录加密的用户 ID
- asp.net - 被 CORS 策略阻止:请求的资源 ASP.Net 上不存在“Access-Control-Allow-Origin”标头
- excel - Workbook.Protect 中的“窗口”是什么意思
- ecmascript-6 - 如何使用 Lightning Web 组件更改所选行的背景颜色?