首页 > 解决方案 > 如何从对象数组中提取键值

问题描述

我有一个对象数组,其格式如下:

{
    "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: 并失败。

我将如何处理这个?

标签: arraysangularkey

解决方案


当您使用这种单线时,您需要遵循特定的语法:

.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 }))

推荐阅读