简体   繁体   English

map 值到 object 内的数组

[英]map values to an array inside an object

I have this object below我下面有这个 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"
                    }
                  ]
                }
              }
            }
          }
        ]
    }
  }
}

There is contents node, each of them will have many viewers, all I want is to extract all viewers name to an array, in this instance my result will be [John, Shaun, Liam]有内容节点,每个节点都有很多观众,我想要的只是将所有观众的名字提取到一个数组中,在这种情况下我的结果将是[John, Shaun, Liam]

I have this approach:我有这种方法:

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]

Which does the job, but occasionaly the object key names change and I have to alter everytime.哪个可以完成工作,但偶尔 object 键名会更改,我每次都必须更改。

So is there more elegant way to do this?那么有没有更优雅的方法来做到这一点?

You can simplify that imperative logic like this.您可以像这样简化命令式逻辑。 I don't understand what you mean by "the object key names change" though我不明白您所说的“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