簡體   English   中英

map 值到 object 內的數組

[英]map values to an array inside an object

我下面有這個 object

{
  "root": {
    "data": {
      "page": 1,
        "contents": [
          {
            "node": {
              "id": "UzpfSTE",
              "stats": {
                "viewers": {
                  "nodes": [
                    {
                      "id": "1",
                      "name": "John"
                    },
                    {
                      "id": "2",
                      "name": "Shaun"
                    }
                  ]
                }
              }
            }
          },
          {
            "node": {
              "id": "UzpfSTG",
              "stats": {
                "viewers": {
                  "nodes": [
                    {
                      "id": "3",
                      "name": "Liam"
                    }
                  ]
                }
              }
            }
          }
        ]
    }
  }
}

有內容節點,每個節點都有很多觀眾,我想要的只是將所有觀眾的名字提取到一個數組中,在這種情況下我的結果將是[John, Shaun, Liam]

我有這種方法:

const data = JSON.parse(rt)

const contents = data.root.data.contents
const newArray = []

for (i = 0; i < contents.length; i++) {
  arr2 = contents[i].node.stats.viewers.nodes
  for (n = 0; n < arr2.length; n++) {
    name = arr2[n].name
    newArray.push(name)
  }
}

console.log(newArray)
>>> [John, Shaun, Liam]

哪個可以完成工作,但偶爾 object 鍵名會更改,我每次都必須更改。

那么有沒有更優雅的方法來做到這一點?

您可以像這樣簡化命令式邏輯。 我不明白您所說的“object 鍵名更改”是什么意思

 const data = { "root": { "data": { "page": 1, "contents": [{ "node": { "id": "UzpfSTE", "stats": { "viewers": { "nodes": [{ "id": "1", "name": "John" }, { "id": "2", "name": "Shaun" } ] } } } }, { "node": { "id": "UzpfSTG", "stats": { "viewers": { "nodes": [{ "id": "3", "name": "Liam" }] } } } } ] } } } const names = data.root.data.contents.flatMap(({ node: { stats: { viewers: { nodes } } } }) => nodes.map(({ name }) => name)) console.log(names)

const data = JSON.parse(rt) const contents = data.root.data.contents const viewers = contents.map(item => item.node.stats.viewers.nodes).flat() const viewerNames = viewers.map(viewer => viewer.name)

暫無
暫無

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

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