Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

获取树结构中的name:getName #47

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

获取树结构中的name:getName #47

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

let data = [
      {
          "name": "1-1",
          "kind": "oo",
          "children": [
              {
                  "name": "2-2",
                  "kind": "ii",

              },
              {
                  "name": "3-3",
                  "children": [
                      {
                          "name": "4-4",
                          "children": [
                              {
                                  "name": '707'
                              }
                          ]
                      }
                  ]
              }
          ]
      },
      {
          "name": "5-5",
      },
      {
          "name": "6-6"
      }
  ]
  function getName(data, key = "name") {
      let result = [];
      if (Array.isArray(data)) {
          for (let item of data) {
              if (item[key]) {
                  result.push(item[key]);
              }
              if (item.children) {
                  result = result.concat(getName(item.children));
              }
          }
          return result;
      } else {
          return result;
      }
  }

  console.log(getName(data))
@kangkang123269
Copy link

function getName(data, key = 'name') {
    const result = []
    const dfs = (node) => { 
        for (const p of node) {
            p.name && result.push(p[key])
            p.children && dfs(p.children)
        }
    }
    Array.isArray(data) && dfs(data)
    return result
}

@lesenelir
Copy link

function getName(data) {
  let res = [],
      len = data.length

  for (let i = 0; i < len; i++) {
    traversal(data[i])
  }

  return res

  function traversal(node) {
    if (!node) return

    res.push(node.name)
    node.children && node.children.forEach(item => {
      traversal(item)
    })
  }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants