簡體   English   中英

如何從 Object 數組中提取鍵值

[英]How to Extract Key Values from an Object Array

我有一個對象數組,其格式如下:

{
    "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 - 解構支架。 在這些括號之間,您可以選擇性地選擇 object 中的屬性。 在您的情況下,您只選擇 ID。

4 - 要選擇的屬性(1 個或多個,逗號分隔)

5 - 寫單行字的粗箭頭

6 - 評估括號:這個有點棘手,堆棧答案甚至不足以解釋它。 最好的理解是玩它。 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而不是 function 主體。

7 - object 聲明的支架

8 - 要使用的屬性。 當編寫單個屬性( { id }而不是{ id: id } )時,它只會減少語法,但會阻止對該變量進行更改。

最終的語法將是

.map(({ id }) => ({ id }))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM